Murdej Ukrutný
Murdej Ukrutný

Reputation: 339

WebClient read content of error page

i have an application that loads the page content. I use the WebClient class. I need to retrieve the contents even when the server returns an error such as 404, 500, ... I need something like this:

WebClient wc = new WebClient();
string pageContent;
try {
    pageContent = wc.DownloadString("http://example.com/page");
}
catch (WebException ex)
{
    pageContent = ex.Response.PageContent; // <-- I need this
}

Upvotes: 2

Views: 948

Answers (1)

aKzenT
aKzenT

Reputation: 7895

You can try this:

WebClient wc = new WebClient();
string pageContent;
try {
    pageContent = wc.DownloadString("http://example.com/page");
}
catch (WebException ex)
{
    Stream receiveStream = ex.Response.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader readStream = new StreamReader( receiveStream, encode );
    pageContent=readStream.ReadToEnd();
}

Upvotes: 6

Related Questions