c# - 从url获取正确的下载文件大小

标签 c# .net http download uwp

我正在尝试从 url ( https://windows.php.net/downloads/releases/php-7.2.9-nts-Win32-VC15-x64.zip ) 获取文件大小,这是我的代码 -

HttpWebRequest request = HttpWebRequest.CreateHttp(url);
HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync());
long length = response.ContentLength;

length 的值为 598 字节,而网站(以及从浏览器下载时)报告的大小为 24.5MB。我什至尝试从响应 header 访问 "Content-Length",但它也有相同的值,598

我错过了什么吗?有没有其他方法可以更准确地获取文件大小?

最佳答案

我使用了您的示例 URL 并通过以下方式阅读了内容:

var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();

我得到的结果是:

20/feb/2018: Hi! We seem to be receiving high volume requests coming from empty user agents. While this shouldn't be an issue, this unfortunately resulted in bandwidth issues on this server causing all downloads to be unavailable. We've therefore decided to temporarily block empty user agents until we upgraded our server bandwidth.

03/mar/2018: We've upgraded the server bandwidth. This is however still not sufficient to handle all empty user agent connections. Please update the user agent in your scripts accordingly or contact us so we can discuss it.

Thank you for your understanding.

它说设置 UserAgent。因此,我将用户代理设置如下:

var request = HttpWebRequest.CreateHttp(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
var response = (HttpWebResponse)(await request.GetResponseAsync());
var length = response.ContentLength;

现在,我得到了 25691309 的正确 Content-Length

我刚刚从以下位置选择了一个用户代理字符串: http://www.useragentstring.com/index.php?id=19879

如果您只对远程文件的大小感兴趣,您应该考虑链接问题的答案。它本质上使用不同的 HTTP 方法(HEAD 与 GET)

        var request = HttpWebRequest.CreateHttp(url);
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
        request.Method = "HEAD";
        using (var response = await request.GetResponseAsync())
        {
            var length = response.ContentLength;
        }

您可以在相关问题中找到有关 HEAD 与 GET 的更多详细信息: http HEAD vs GET performance

关于c# - 从url获取正确的下载文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027632/

相关文章:

c# - 学习WM6的书籍

c# - 幕后的new和override到底发生了什么?

c# - VS2010 C#函数使用循环

c# - 识别事件网络接口(interface)

c# - WebApi 应用程序 : Error 404. 0,处理程序静态文件

c# - 为什么这个ajax调用失败了?

c# - 我可以将枚举传递给 Controller ​​以便模型绑定(bind)器绑定(bind)它吗?

ruby :Net::HTTP.start 问题

c# - 在重定向时保持 HTTP 基本身份验证有效

json - 从 POST 解析 JSON