In this article I am going to explain how we can use the power of .Net framework class library for downloading the images imposed on a web page. There is a class called WebBrowser. Check here for msdn documentation.
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
browser.Navigate(“http://www.msn.com”);
In the above code snippet, I am creating a new WebBrowser object. After that registering DocumentCompleted event. Now the most important statement, WebBrowser.Navigate, this method will accept a url and will load the webpage. Once the entire webpage is loaded, DocumentCompleted event will get fired. In this method we will do as follow
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)First we will convert the sender object to a WebBrowser. Then we will get all the img tag’s in the loaded webpage. For each img tag we will use the WebClient object to download the image. We will be downloading the file to the current working directory.
{
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('/')));
}
}