C#停止一个无限的foreach循环

时间:2013-07-26 21:58:33

标签: c# foreach

此foreach循环检查网页并查看是否有任何图像然后下载它们。我怎么阻止它?当我按下按钮时,它会永远继续循环。

 private void button1_Click(object sender, EventArgs e)
    {
        WebBrowser browser = new WebBrowser();
        browser.DocumentCompleted +=browser_DocumentCompleted;
        browser.Navigate(textBox1.Text);           
    }

    void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser browser = sender as WebBrowser;
        HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
        WebClient webClient = new WebClient();

        int count = 0; //if available
        int maximumCount = imgCollection.Count;
        try
        {
                foreach (HtmlElement img in imgCollection)
                {
                    string url = img.GetAttribute("src");
                    webClient.DownloadFile(url, url.Substring(url.LastIndexOf('/')));

                     count++;
                     if(count >= maximumCount)
                          break;
                }
        }
        catch { MessageBox.Show("errr"); }
    }

3 个答案:

答案 0 :(得分:0)

使用break;关键字来摆脱循环

答案 1 :(得分:0)

您没有无限循环,根据您将文件写入磁盘的方式抛出异常

private void button1_Click(object sender, EventArgs e)
{
    WebBrowser browser = new WebBrowser();
    browser.DocumentCompleted += browser_DocumentCompleted;
    browser.Navigate("www.google.ca");
}

void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser browser = sender as WebBrowser;
    HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
    WebClient webClient = new WebClient();

    foreach (HtmlElement img in imgCollection)
    {
        string url = img.GetAttribute("src");
        string name = System.IO.Path.GetFileName(url);
        string path = System.IO.Path.Combine(Environment.CurrentDirectory, name);
        webClient.DownloadFile(url, path);
    }
}

该代码在我的环境中运行良好。您似乎遇到的问题是当您设置DownloadFile filepath时,您将其设置为类似`\ myimage.png'的值,并且webclient无法找到路径,因此它会抛出异常。

上面的代码将其放入当前目录中,扩展名为。

答案 2 :(得分:0)

可能是事件browser.DocumentCompleted导致错误,如果页面刷新,则事件再次被触发。您可以尝试取消注册该事件。

void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{    
    WebBrowser browser = sender as WebBrowser;

    browser.DocumentCompleted -= browser_DocumentCompleted;

    HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
    WebClient webClient = new WebClient();

    foreach (HtmlElement img in imgCollection)
    {
        string url = img.GetAttribute("src");
        string name = System.IO.Path.GetFileName(url);
        string path = System.IO.Path.Combine(Environment.CurrentDirectory, name);
        webClient.DownloadFile(url, path);
    }
}