FJam
FJam

Reputation: 756

Image download null reference exception

I am trying to create an image downloader. Basically it is supposed to go through a website and download all of the images. The error I get is in the first line of the foreach loop, 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('/')));
    }
}

Upvotes: 0

Views: 440

Answers (3)

G.Y
G.Y

Reputation: 6159

change this:

img.FirstChild.GetAttribute("src");

to that:

img.GetAttribute("src");

Upvotes: 3

Ehsan
Ehsan

Reputation: 32651

change this

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

to

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

as img doesn't have childrens.

Upvotes: 0

SLaks
SLaks

Reputation: 887205

<img> elements do not have children.

Upvotes: 3

Related Questions