How to request only the HTTP header with C#?

19,197

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.).

Share:
19,197
Jader Dias
Author by

Jader Dias

Perl, Javascript, C#, Go, Matlab and Python Developer

Updated on June 10, 2022

Comments

  • Jader Dias
    Jader Dias almost 2 years

    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;
    }