How to request only the HTTP header with C#?

Jader Dias picture Jader Dias · Jun 4, 2011 · Viewed 18.6k times · Source

I want to check if the URL of a large file exists. I'm using the code below but it is too slow:

public static bool TryGet(string url)
{
    try
    {
        GetHttpResponseHeaders(url);
        return true;
    }
    catch (WebException)
    {
    }

    return false;
}

public static Dictionary<string, string> GetHttpResponseHeaders(string url)
{
    Dictionary<string, string> headers = new Dictionary<string, string>();
    WebRequest webRequest = HttpWebRequest.Create(url);
    using (WebResponse webResponse = webRequest.GetResponse())
    {
        foreach (string header in webResponse.Headers)
        {
            headers.Add(header, webResponse.Headers[header]);
        }
    }

    return headers;
}

Answer

Teoman Soygul picture Teoman Soygul · Jun 4, 2011

You need to set:

webRequest.Method = "HEAD";

This way the server will respond with the header information only (no content). This is also useful to check if the server accepts certain operations (i.e. compressed data etc.).