user5405648
user5405648

Reputation:

Read source code of 404 page using WebClient in C#?

I have a site that returns a custom 404 page, I need to get the source code of it and determine what kind of 404 it's returning. Is there a way to get the source code of the 404 page?

try
{
    using (var webClient = new WebClient())
    {
        webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
        webClient.DownloadFile(new Uri(file.Address), file.SaveLocation);
    }
}
catch (WebException e)
{
    // read source code here...
}

Upvotes: 0

Views: 94

Answers (1)

Francesco B.
Francesco B.

Reputation: 3097

This is a solution (tested), which in all fairness @KamilJarosz hinted in a comment to your question:

...
catch (WebException e)
{
    if (e.Response != null && (e.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
    {
        var Html404Page = new StreamReader(e.Response.GetResponseStream()).ReadToEnd().ToString();
    }
}

Of course I thought you wanted a string, so I adapted the answer to this question.

EDIT

I also added a guard clause, to prevent further problems if the Response is null and processing if the response is not a 404 one.

Upvotes: 1

Related Questions