Getting a header/filesize in .NET

回眸只為那壹抹淺笑 提交于 2019-12-12 01:17:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!