Home » c# » How to get the file size from http headers

How to get the file size from http headers

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to get the size of an http:/…/file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?

Answers:

Yes, assuming the HTTP server you’re talking to supports/allows this:

System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http://stackoverflow.com/robots.txt");
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
    int ContentLength;
    if(int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
    { 
        //Do something useful with ContentLength here 
    }
}

If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.

Questions:
Answers:

Can this be done with HTTP headers?

Yes, this is the way to go. If the information is provided, it’s in the header as the Content-Length. Note, however, that this is not necessarily the case.

Downloading only the header can be done using a HEAD request instead of GET. Maybe the following code helps:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/");
req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)(req.GetResponse());
long len = resp.ContentLength;

Notice the property for the content length on the HttpWebResponse object – no need to parse the Content-Length header manually.

Questions:
Answers:
WebClient webClient = new WebClient();
webClient.OpenRead("http://stackoverflow.com/robots.txt");
long totalSizeBytes= Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]);
Console.WriteLine((totalSizeBytes));