C# WebClient.DownloadString(url)当此url返回404页时,如何跳过此操作?

C# WebClient.DownloadString(url)当此url返回404页时,如何跳过此操作?,c#,http-status-code-404,webclient,C#,Http Status Code 404,Webclient,我使用WebClient.DownloadString(url)来下载一个网页,当一个url链接到404网页时,它停止工作,不再工作。 当我遇到这个错误时,我想跳过这些页面 如果url为404页,则不会开始下载。因此,我无法解析未下载的数据…您可以将代码放入Try…Catch块并捕获一个。如果您想更多地控制如何处理特定错误,可以使用WebException的Status属性返回枚举。您必须捕获异常并测试404: try { string myString; using (WebC

我使用WebClient.DownloadString(url)来下载一个网页,当一个url链接到404网页时,它停止工作,不再工作。 当我遇到这个错误时,我想跳过这些页面


如果url为404页,则不会开始下载。因此,我无法解析未下载的数据…

您可以将代码放入
Try…Catch
块并捕获一个。如果您想更多地控制如何处理特定错误,可以使用WebException的
Status
属性返回枚举。

您必须捕获异常并测试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;
}

请不要在标题前加上“C#”之类的前缀。这就是标签的用途。我在我的项目中尝试过这个答案。但它和404在一起时就崩溃了。错误。我是不是要把球扔出去?或者有没有更优雅的方式来接近它。