How to get website header information in C#

With the following function you can easily retrieve a list of website headers in C#. The function needs only the url of a webpage to collect the data. If the function is successfully executed, you’ll get a Dictionary, typed as <string, string>, as return value. This Dictionary<string, string> contains all the headers of the webpage, whose url you passed by at function call time.

//Don't forget to set the using-directive ;)
using System.Net;

//...

public Dictionary getHeaders(string url)
{
    //Dictionary which shall contain the header information
    Dictionary header = new Dictionary();

    //Create webrequest
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

    //Create response object
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    //Read all headers from the response
    foreach (string headerItem in response.Headers)
    {
        //Add header to the dictionary
        header.Add(headerItem, response.Headers[headerItem]);
    }

    //Close webrequest
    response.Close();

    //return header information
    return header;
}

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked