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

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

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

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

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