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?
Thanks!
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?
Thanks!
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());
int len = resp.ContentLength;
/EDIT: Completed the code. Notice the extra property for the content length on the HttpWebResponse
object!
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";
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.