Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 图像下载空引用异常_C#_Webclient Download - Fatal编程技术网

C# 图像下载空引用异常

C# 图像下载空引用异常,c#,webclient-download,C#,Webclient Download,我正在尝试创建一个图像下载程序。基本上,它应该通过一个网站下载所有的图片。我得到的错误在foreach循环的第一行,System.NullReferenceException private void button1_Click(object sender, EventArgs e) { WebBrowser browser = new WebBrowser(); browser.DocumentCompleted += browser_DocumentCompleted;

我正在尝试创建一个图像下载程序。基本上,它应该通过一个网站下载所有的图片。我得到的错误在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('/')));
    }
}
元素没有子元素。

元素没有子元素。

更改此项:

img.FirstChild.GetAttribute("src");
为此:

img.GetAttribute("src");
更改此项:

img.FirstChild.GetAttribute("src");
为此:

img.GetAttribute("src");
改变这个

 string url = img.FirstChild.GetAttribute("src");

因为img没有孩子。

更改此选项

 string url = img.FirstChild.GetAttribute("src");


因为img没有子对象。

使用调试器找出什么是空的。使用调试器找出什么是空的。现在在修复后,我在下一行得到了这个错误
'System.Net.WebException'
webClient.DownloadFile(url,url.Substring(url.LastIndexOf('/'))那么url中存储了什么?假设我把google.com作为url,它应该在homepageumm上下载图像。。好吧,让我们假设一个这样的网站?它将如何自动下载“/”之后的所有图像?根据您的代码,您有一个循环,可以针对根目录下的每个图像对网站进行迭代:即:www.google.com/mypic1.png,www.google.com/mypic2.png等。根据示例,您的代码似乎试图在mypic2.png之后从www.google.com下载mypic1.png,这里的问题是什么?现在在修复后,我在下一行得到了这个错误
'System.Net.WebException'
,webClient.DownloadFile(url,url.Substring(url.LastIndexOf('/'))那么url中存储了什么?假设我把google.com作为url,它应该在homepageumm上下载图像。。好吧,让我们假设一个这样的网站?它将如何自动下载“/”之后的所有图像?根据您的代码,您有一个循环,可以针对根目录下的每个图像对网站进行迭代:即:www.google.com/mypic1.png,www.google.com/mypic2.png等。根据示例,您的代码似乎试图在mypic2.png之后从www.google.com下载mypic1.png,这里的问题是什么?