问题
I have a link to two files. They may be the same file, but they may not be the same URL. I want to figure out if they are the same by checking the content-length before doing a full download. What's the best way to do this?
Currently I am using webbrowser control to load the page and extract data and then using WebClient.Download
to get the file. Is there a way I can use WebClient to check the filesize before downloading the entire file?
回答1:
I found an excellent article, Get file length over HTTP before you download it, which provides a way that works very well for me:
static public long GetFileSize(string url)
{
using (WebClient obj = new WebClient())
using (Stream s = obj.OpenRead(url))
return long.Parse(obj.ResponseHeaders["Content-Length"].ToString());
}
回答2:
Equality of lengths does not mean that files are identical. However, if you're sure that this is enough to assert equality, you can issue a HttpWebRequest
with Method
set to HEAD
: this will only download file headers, including content-length
.
来源:https://stackoverflow.com/questions/1176928/getting-a-header-filesize-in-net