We help IT Professionals succeed at work.

How do I download all images from a web page in C# using WPF?

rye004
rye004 asked
on
I am trying to write a program using C# and WPF to download all images from a web page.

In my XAML I added the following control:

<WebBrowser x:Name="scrapeWebBrowser" Grid.Column="1" Grid.Row="1"/>

Open in new window


For testing, I created a test button that does the following:

scrapeWebBrowser.Navigate("http://yahoo.com");
HTMLDocument objHtmlDocument = (HTMLDocument)scrapeWebBrowser.Document;

foreach (IHTMLElementCollection imageElements in objHtmlDocument.images)
{
//I am not sure what to do here.  I am trying to get the reference to the image.
}

Open in new window


How do I get a reference in my code above?  Once I have the reference, how do I download it?

Any direction would be greatly appreciated.      

Many Thanks!
Comment
Watch Question

Software Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT
Commented:
you can try something like this:

HTMLDocument objHtmlDocument = (HTMLDocument)scrapeWebBrowser.Document;
            foreach (HTMLImgClass imageElements in objHtmlDocument.images)
            {
                WebClient client = new WebClient();
                String fileName = System.IO.Path.GetFileName(imageElements.href);
                client.DownloadFileAsync(new Uri(imageElements.href), System.IO.Path.Combine(@"C:\yourPath\", fileName));
            }

Open in new window

Author

Commented:
Thanks!  I did have to set the property for “Embedded Interop Types” to “False” under the reference for Microsoft.mshtml.
Ryan ChongSoftware Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT

Commented:
I did have to set the property for “Embedded Interop Types” to “False” under the reference for Microsoft.mshtml.

yes, you're correct on that!