WebClient.DownloadString(url)当这个url返回404页面时,我怎么能跳过这个?

Has*_*kır 3 c# webclient http-status-code-404

我正在使用WebClient.DownloadString(url)下载一个网页,当一个网址停止并且不再起作用的404网页时.当我遇到这个错误时,我想跳过这些页面.

如果网址是404页面,则不会开始下载.所以我无法解析未下载的数据......

Bro*_*ass 12

您必须捕获异常并测试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;
}
Run Code Online (Sandbox Code Playgroud)