2017-02-14 6 views
0

複数のリンクがあり、開始ボタンを押すとすべてのリンクを処理します。いずれかのリンクが404を返した場合は、スキップして次のページに移動します。404が発生したときにforループが停止するのを防ぐには?

私の現在のコードは次のようである:

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; 
      } 

エラーがNo enclosing loop out of which to break or continueを言っ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; 
    } 

} 
関連する問題