gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:56 29 4
gpt4 key购买 nike

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

    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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com