title | author | date | CreateTime | categories |
WPF 获取下载内容长度 | lindexi | 2018-11-08 20:18:15 +0800 | 2018-11-08 20:15:15 +0800 | WPF |
本文告诉大家如何获取一个下载内容的长度
在 WPF 可以通过 System.Net 的类进行下载资源,如下载一张图片 http://image.acmx.xyz/lindexi%2F2018116203842298 可以使用下面的代码,通过 ContentLength 拿到下载的内容长度
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
var url = "http://image.acmx.xyz/lindexi%2F2018116203842298";
var request = WebRequest.CreateHttp(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
request.Method = "Get";
using (var response = await request.GetResponseAsync())
{
var length = response.ContentLength;
}
}
这里的 ContentLength 就是内容的长度,注意很多的网站都需要使用 UserAgent 可以从 UserAgentString 找到很多可以使用的资源
实际上面的代码可以使用 HEAD 代替 get 方法,请看下面
var url = "http://image.acmx.xyz/lindexi%2F2018116203842298";
var request = WebRequest.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;
}
具体请看 HTTP协议中POST、GET、HEAD、PUT等请求方法及相应值得含义 - 空白_回忆的博客
c# - Getting correct download file size from url - Stack Overflow