WebClient.DownloadString(url) when this url returns a 404 page, how can i skip this?

有些话、适合烂在心里 提交于 2019-11-28 10:32:43

You will have to catch the Exception and test for a 404:

try
{
    string myString;
    using (WebClient wc = new WebClient())
        myString= wc.DownloadString("http://foo.com");

}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
    {
        var resp = (HttpWebResponse)ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
        {
            //the page was not found, continue with next in the for loop
            continue;
        }
    }
    //throw any other exception - this should not occur
    throw;
}

You can put your code in a Try...Catch block and catch a WebException. If you want more control on how to handle specific errors, you can use the WebException's Status property which returns a WebExceptionStatus enumeration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!