0

この foreach ループは Web ページをチェックし、画像があるかどうかを確認してからダウンロードします。どうすれば止められますか? ボタンを押すと、ループが永遠に続きます。

 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"); }
    }
4

3 に答える 3

0

キーワードを使用しbreak;てループから抜け出します

于 2013-07-26T22:01:20.070 に答える
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);
    }
}
于 2013-07-26T23:51:55.633 に答える