我正在开发xamarin.forms应用程序。我想使用HttpClient同时下载多个文件。如果有多个文件,那么我就会得到.NET Framework 2.0的文件。System.IO.IOException:Sharing violation on path(违反路径共享)。 . 有什么需要改进的地方吗?这是我下载文件的代码。
public async Task DownloadFileAsync(string sourceUrl, string filePathWhereToSave, CancellationTokenSource cts)
{
Exception error = null;
bool isCancelled = false;
try
{
if (!downloadingTasks.ContainsKey(sourceUrl))
downloadingTasks.Add(sourceUrl, cts);
var token = cts.Token;
var response = await _client.GetAsync(sourceUrl, HttpCompletionOption.ResponseHeadersRead, token);
response.EnsureSuccessStatusCode();
string fileName = filePathWhereToSave.Substring(filePathWhereToSave.LastIndexOf('/'));
string directory = filePathWhereToSave.Substring(0, filePathWhereToSave.LastIndexOf('/'));
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
var totalData = response.Content.Headers.ContentLength.GetValueOrDefault(-1L);
var canSendProgress = totalData != -1L;
await Task.Run(async() =>
{
using (var fileStream = OpenStream(filePathWhereToSave))
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
var totalRead = 0L;
var buffer = new byte[bufferSize];
var isMoreDataToRead = true;
do
{
var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
if (read == 0)
isMoreDataToRead = false;
else
{
await fileStream.WriteAsync(buffer, 0, read);
totalRead += read;
if (canSendProgress)
{
//var progress = ((totalRead * 1d) / (totalData * 1d) * 100);
MessagingCenter.Send<DownloadFileProgressChangedMessage>(new DownloadFileProgressChangedMessage(sourceUrl, totalRead, totalData, 0), MessageNameConstants.DownloadFileProgressChangedMessage);
}
}
} while (isMoreDataToRead);
}
}
});
}
catch (OperationCanceledException ex)
{
isCancelled = true;
}
catch (Exception e)
{
error = e;
System.Diagnostics.Debug.WriteLine(e.ToString());
}
finally
{
MessagingCenter.Send<DownloadCompletedMessage>(new DownloadCompletedMessage(sourceUrl, filePathWhereToSave, error, isCancelled), MessageNameConstants.DownloadCompletedMessage);
if (downloadingTasks.ContainsKey(sourceUrl))
downloadingTasks.Remove(sourceUrl);
}
}
这可能是由于文件将被读流锁定,所以写流不能被创建而出现异常。
为了避免这种情况,你可以使用FileStream类启用读写访问。
FileStream fileStream = new FileStream(filePathWhereToSave,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
或者使用 StreamWriter
using (var writer = new StreamWriter(filePathWhereToSave))
{
// do work here.
}
另外,什么是 OpenStream
? 我在任何汇编中都找不到它,它是否包含在第三方库中?
请参考