小编Dra*_*ako的帖子

下载时 HttpClient 未写入流

目前我正在实施一种使用 HttpClient 报告进度的方法,因为我们与 .NET4 WPF 和 Windows 通用应用程序共享代码,我们使用来自 NuGet 的 Microsoft HTTP 客户端库。这个想法是将目标文件流包装在 a 中CountingInputStream并在那里报告进度:

 public override void Write(byte[] buffer, int offset, int count)
    {
        _stream.Write(buffer, offset, count);

        _bytesRead += count;
        _progress.Report(_bytesRead);

        if (_cancellationToken.IsCancellationRequested)
        {
            _cancellationToken.ThrowIfCancellationRequested();
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后我发送我的请求: HttpResponseMessage httpResponseMessage = AsyncHelpers.RunSync(() => _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken));

之后,我打开文件流,然后复制内容流。响应具有正确的标头: Content-Length: 213334 Content-Type: application/octet-stream; charset=UTF-8 Content-Disposition: attachment; filename="Bondi Beach.jpg"; filename*=UTF-8''Bondi%20Beach.jpg

using(Stream fileStream = new CountingInputStream(storage.Open(downloadRequest.TargetPath, FileMode.Create), downloadRequest.Progress, cancellationToken )) {                                               
                await HttpHeaderResponseMessage.Content.CopyToAsync(fileStream);
       }
Run Code Online (Sandbox Code Playgroud)

问题是StreamContent只有在下载完成后才开始写入文件流。当它开始编写进度报告时,它工作正常。

我已经尝试过不同的方法,例如:

  • ReadAsStreamAsync 然后将响应流复制到文件流
  • ReadAsStreamAsync …

c# http stream dotnet-httpclient win-universal-app

2
推荐指数
1
解决办法
5710
查看次数

标签 统计

c# ×1

dotnet-httpclient ×1

http ×1

stream ×1

win-universal-app ×1