CopyToAsync之后文件为空

时间:2019-01-14 16:19:35

标签: c# .net

方法是从HTTP服务器将文件下载到本地文件系统。高负载时,一些下载的文件为空。下载后立即访问文件。

 private static Task<FileHolderModel> DownloadFile(string downloadUrl)
   {
       return Client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).ContinueWith(task =>
       {
           using (var response = task.Result)
           {
               var originalFileName = ReadFileName(response);
               var fullName = Path.Combine(Helper.CreateTempFolder(), $"{Guid.NewGuid()}{Path.GetExtension(originalFileName)}");
               using (var fileStream = File.Open(fullName, FileMode.Create))
               {
                   response.Content.CopyToAsync(fileStream).Wait();
                   fileStream.Flush(true);
               }
               return new FileHolderModel(fullName, originalFileName);
           }
       });
   }

什么可能导致空文件?

1 个答案:

答案 0 :(得分:3)

您在这里有些混乱,可能是因为您在其中使用ContinueWith以及.Wait()。如果使用await并完全删除ContinueWith块,则此功能将更加简单易读。例如:

private static async Task<FileHolderModel> DownloadFile(string downloadUrl)
             //^^^^^ make it an async method
{
    var response = await Client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);
                 //^^^^^ await this call
    var originalFileName = ReadFileName(response);
    var fullName = Path.Combine(/* snip */);

    using (var fileStream = File.Open(fullName, FileMode.Create))
    {
        await response.Content.CopyToAsync(fileStream);
      //^^^^^ await this call too
        fileStream.Flush(true); //This is probably not needed
    }

    return new FileHolderModel(fullName, originalFileName);    
}