我正在使用WebClient.DownloadString(url)下載一個網頁,當一個網址404網頁停止並且不再工作。 當我收到這個錯誤時,我想跳過這些頁面。WebClient.DownloadString(url)當這個url返回一個404頁面,我怎麼跳過這個?
如果url是404頁面,它不會開始下載。所以我不能解析未加載的數據...
我正在使用WebClient.DownloadString(url)下載一個網頁,當一個網址404網頁停止並且不再工作。 當我收到這個錯誤時,我想跳過這些頁面。WebClient.DownloadString(url)當這個url返回一個404頁面,我怎麼跳過這個?
如果url是404頁面,它不會開始下載。所以我不能解析未加載的數據...
你將不得不捕獲異常,並測試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;
}
我在我的項目中試過這個答案。但它與404.錯誤一起在崩潰。我只是刪除投擲?還是有更接近它的更優雅的方式。 – Decoder94 2017-06-22 14:46:57
你可以把你的代碼放在Try...Catch
區塊中,並捕獲WebException。如果您想要更好地控制如何處理特定錯誤,則可以使用WebException的Status
屬性,該屬性返回WebExceptionStatus枚舉。
請不要用「C#」和這樣的前綴您的圖書。這就是標籤的用途。 – 2012-01-18 19:07:02