c# - HttpClient : limit response (downloaded file) size while using HttpResponseMessage. 内容.ReadAsStreamAsync()

标签 c# dotnet-httpclient

我正在寻找一种方法来控制下载文件的大小,同时使用以下代码:

    var client = new HttpClient();

    HttpResponseMessage resp = await client.GetAsync(mediaUri, HttpCompletionOption.ResponseHeadersRead);

    using (var fileStream = File.Create(outputPath))
    {
        using (var httpStream = await resp.Content.ReadAsStreamAsync())
        {
            httpStream.CopyTo(fileStream);
            fileStream.Flush();
        }
    }

如何防止下载大于预定义大小的文件?

编辑:

在下面的答案出现之前,我求助于用这个替换 CopyTo。我把它放在这里可能是为了根据以下答案对 ProgressMessageHandler 进行加权:

            using (var fileStream = File.Create(outputPath))
            {
                using (var httpStream = await resp.Content.ReadAsStreamAsync())
                {
                    // instead of httpStream.CopyToAsync(fileStream);
                    byte[] buffer = new byte[65536];
                    while (true)
                    {
                        int read = await httpStream.ReadAsync(buffer, 0, buffer.Length, ct);
                        if (read <= 0)
                            break;

                        // do the policing here

                        await fileStream.WriteAsync(buffer, 0, read);
                    }
                    fileStream.Flush();
                }
            }

最佳答案

尝试检查 the resp.Content.Headers.ContentLength property ,其中应包含文件的大小(以字节为单位)。

关于c# - HttpClient : limit response (downloaded file) size while using HttpResponseMessage. 内容.ReadAsStreamAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664793/

相关文章:

c# - 使主窗口处于非事件状态的选项卡上的 WebBrowser 控件

c# - Linq:添加额外的 'Where' 子句给出随机结果

c# - 将 httpclient 与 polly 策略一起使用时未捕获 TaskCanceledException

c# - 尝试在非 HttpClient 套接字上进行操作

c# - 什么是有效的 Entity Framework 查询来检查用户是否是 friend ?

c# - 如何更改 ToolTip 在 TreeView 上的位置?

c# - 如何在单独的页面中显示我的产品?

c# - Xamarin 表单 HTTPClient 调用崩溃

c# - 在 HttpClient 中覆盖主机

c# - 如何复制 HttpContent 异步和可取消?