2017-02-14 59 views
0

我有多個鏈接,我想在按下開始按鈕時處理所有這些鏈接。如果其中一個鏈接返回404,我想跳過它並移動到下一個。如何防止發生404時循環停止?

我當前的代碼如下:

try 
      { 
       foreach (string s in txtInstagramUrls.Lines) 
       { 
        if (s.Contains("something")) 
        { 
         using (WebClient wc = new WebClient()) 
         { 
          Match m = Regex.Match(wc.DownloadString(s), "(?<=og:image\" content=\")(.*)(?=\" />)", RegexOptions.IgnoreCase); 
          if (m.Success) 
          { 
           txtConvertedUrls.Text += m.Groups[1].Value + Environment.NewLine; 
          } 
         } 
        } 
       } 
      } 
      catch(WebException we) 
      { 
       if(we.Status == WebExceptionStatus.ProtocolError && we.Response != null) 
       { 
        var resp = (HttpWebResponse)we.Response; 
        if (resp.StatusCode == HttpStatusCode.NotFound) 
        { 
         continue; 
        } 
       } 
       throw; 
      } 

錯誤顯示了continue;No enclosing loop out of which to break or continue。我不知道如何從這裏開始。任何幫助表示讚賞。

回答

3

這是因爲拋出異常時,您已經離開foreach塊,並且您正在嘗試continue,但此時沒有循環可繼續。這裏被簡化您的代碼,以顯示此:

try { 
    foreach(string s in txtInstagramUrls.Lines) { 

    } 
} 
catch(WebException we) { 
    // There is no loop here to continue 
} 

你需要把循環內的嘗試:

foreach(string s in txtInstagramUrls.Lines) { 
    try { 
     // do something 
    } 
    catch(WebException we) { 
     continue; 
     throw; 
    } 
} 

所以,你需要更改您的代碼如下:

foreach(string s in txtInstagramUrls.Lines) { 
    try { 
     if(s.Contains("something")) { 
     using(WebClient wc = new WebClient()) { 
      Match m = Regex.Match(wc.DownloadString(s), "(?<=og:image\" content=\")(.*)(?=\" />)", RegexOptions.IgnoreCase); 
      if(m.Success) { 
       txtConvertedUrls.Text += m.Groups[ 1 ].Value + Environment.NewLine; 
      } 
     } 
     } 
    } 
    catch(WebException we) { 
     if(we.Status == WebExceptionStatus.ProtocolError && we.Response != null) { 
     var resp = (HttpWebResponse) we.Response; 
     if(resp.StatusCode == HttpStatusCode.NotFound) { 
      continue; 
     } 
     } 
     throw; 
    } 

}