8/28/2010

Get File Length over http before you download it

This is one of those forum questions that you “think” you know the answer to, and then you’re proven wrong.
User wants to download a file from a remote site but they do not want to proceed with the download if the file is larger than 10MB. Make sense, right?
I said there was no way to do this without downloading the file. I was wrong. Here’s how he solved his own problem:
static void Main(string[] args)
{
string completeUrl = 
"http://www.eggheadcafe.com/FileUpload/1145921998_ObjectDumper.zip";
WebClient obj = new WebClient();
Stream s = obj.OpenRead(completeUrl);
Console.WriteLine( obj.ResponseHeaders["Content-Length"].ToString());
s.Close();
obj = null;
Console.ReadLine();
}

The above correctly reports the file size of 85,827 bytes without ever downloading the file!

Somebody had a problem. Instead of giving up (or worse, taking my so-called “expert advice”) he thought  “outside the box” and found a solution. I call that outstanding!

NOTE: At least one commenter pointed out that a HEAD request is the most efficient. That's true, but in my experience not all HEAD requests work on all sites so you actually may need to make 2 requests if the first one fails.