如何防止404发生时循环停止?

时间:2017-02-14 01:16:57

标签: c# http for-loop try-catch webclient

我有多个链接,我想在按下开始按钮时处理所有这些链接。如果其中一个链接返回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。我不知道如何从这里开始。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

这是因为当抛出异常时,您已经离开了foreach块并且您正在尝试continue但是此时没有循环继续。这是您的代码简化以显示:

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

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

你需要把try放在循环中:

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

}