【发布时间】:2013-07-27 08:00:22
【问题描述】:
此 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"); }
}
【问题讨论】:
-
你说的“按钮”是什么?
-
你想什么时候停止?
-
这在我看来不像是无限循环......
-
你能贴出
imgCollection的填充代码吗? -
你确定这不只是需要很长时间吗?你试过断点吗?