WebClient读取错误页面的内容

时间:2012-04-01 01:33:14

标签: c# .net

我有一个加载页面内容的应用程序。我使用WebClient类。即使服务器返回错误,例如404,500,...,我也需要检索内容... 我需要这样的东西:

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

1 个答案:

答案 0 :(得分:6)

你可以试试这个:

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