0

我正在研究 xamarin.forms 应用程序。我想使用 HttpClient 同时下载多个文件。如果有多个文件,那么我得到: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);
        }
    }       
4

1 回答 1

0

这可能是因为文件被读取流锁定,因此无法创建写入流并且您得到异常。

为避免这种情况,您可以使用 FileStream 类启用读/写访问。

  FileStream fileStream = new FileStream(filePathWhereToSave,
                                   FileMode.OpenOrCreate,
                                   FileAccess.ReadWrite,
                                   FileShare.None);

或使用StreamWriter

using (var writer = new StreamWriter(filePathWhereToSave))
{
   // do work here.
}

顺便说一句,什么是OpenStream?我在任何程序集中都找不到它,它是否包含在第三方库中?


参考

https://stackoverflow.com/a/23779697/8187800

https://stackoverflow.com/a/11541330/8187800

于 2020-06-19T09:00:38.223 回答