Recently I had to write a feed generating tool for the Dundee Mercury web site. One of the things this tool had to do was to work out the size of a file pointed to by a given url, but I didn't want to download the whole file as it was a several megabyte long video file.

Turns out, the way to do it is to send the HTTP HEAD request and then access the ContentLength attribute. The code below does it in C# 2.0

HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url_to_file);
hwr.Method = "HEAD";
HttpWebResponse hwrp = (HttpWebResponse)hwr.GetResponse();
string length =
    hwrp.contentLength.ToString(CultureInfo.CurrentCulture);
hwrp.close();

Technorati tags: ,