ASP.NET: Get the size of a file without downloading it

By Peter Bromberg

Some time ago I made a post on this subject, and I revisited it to check on timings. An easy way to get the size of a file over the web is to make a HEAD request for the resource and then examine the Content-Length Header. But there is another way: You can open a WebRequest, get the Response, examine ResponseHeaders["Content-Length"], and then immediately close the stream without reading any of it. Which do you think is faster?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace HEADRequest
{
    class Program
    {
         static void Main(string[] args)
        {
             var completeUrl = "http://www.eggheadcafe.com/FileUpload/1145921998_ObjectDumper.zip";
            long head=0;
             long stm=0;
             string length = String.Empty;
           string length2 = String.Empty ;
            for (int i = 0; i < 10; i++)
            {
                Stopwatch sw = Stopwatch.StartNew();
                 var request = WebRequest.Create(completeUrl);
                 request.Method = "HEAD";
                 var response = request.GetResponse();
                 length = response.Headers[HttpResponseHeader.ContentLength];
                 sw.Stop();
                 response.Close();
                head += sw.ElapsedTicks;
        
                Stopwatch sw2 = Stopwatch.StartNew();
               WebClient obj = new WebClient();
               Stream s = obj.OpenRead(completeUrl);
                sw2.Stop();
                stm += sw2.ElapsedTicks;
                 length2 = obj.ResponseHeaders["Content-Length"].ToString();
                 s.Close();
                 obj.Dispose();
            }
           Console.WriteLine("HEAD: " + head.ToString( ) + " :" + length);
           Console.WriteLine("STREAM: " + stm.ToString() + " : " + length2);
             // OUTPUT:
            // HEAD:   3403088
            // STREAM: 2192986
            // HEAD is 55 percent slower
           Console.ReadLine();
        }
     }
}


The answer is, it's faster to open the stream, examine the header, and immediately close the stream, instead of issuing a HEAD request!

ASP.NET: Get the size of a file without downloading it  (2156 Views)