我正在尝试创建一个图像下载器。基本上它应该通过一个网站并下载所有图像。我得到的错误是在 foreach 循环的第一行,System.NullReferenceException
.
private void button1_Click(object sender, EventArgs e)
{
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate("http://www.mysite.com");
}
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.FirstChild.GetAttribute("src");
webClient.DownloadFile(url, url.Substring(url.LastIndexOf('/')));
}
}