c# winforms webbrowser control - how to download an image? - c#

In a Winforms app I have a webbrowser control that is logged in to a site.
Now I want to download an image (that can only be downloaded when logged in to that site) programmatically.
So how do I tell my webbrowser control to download an image, ie. http://www.example.com/image.jpg, and save it somewhere ?

If you don't want to save the file directly to your hard drive, you can download it into a stream. e.g.
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData("http://www.example.com/image.jpg");
Bitmap b = new Bitmap(new MemoryStream(bytes));
If you then wish to save it to your hard drive, you can call the Bitmap.Save() method. e.g.
b.Save("bitmap.jpg");

I guess you can't do that silently using a WebBrowser. Don't forget that it's an IE instance at the end. What you can do is: Navigate to the ImageURL, then Invoke ShowSaveAsDialog() that will show a Save as dialog to the user to save the Image:
WebBrowser wb = new WebBrowseR();
wb.Navigate("ImageURL");
wb.ShowSaveAsDialog();
A better solution is to get the Image using a WebClient
System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("username", "password"); //Authenticates to the website - Call it only if the image url needs authentication first
wc.DownloadFile("imageURL", "downloadedImage.jpg"); //Downloads the imageURL to the local file downloadedImage.jpg

Related

How do I open a url that downloads a file in WebBrowser and saves the file (without being prompted about the path)?

When I open a link that downloads a file in a WebBrowser, I'm asked to select the path to save the file. How can I do this automatically, i.e. save it in the path specified by me without being asked about it?
WebBrowser wb = new WebBrowser();
Uri uri = new Uri(url);
wb.Url = uri;
You can use Navigating & DownloadFileCompleted events of WebBrowser control. In the Navigating event, you can apply If condition to check file-type.
Visit Open/Save WebBrowser Control Dialog Box for example of downloading zip file.

Programmatically open webpage from file and click link to handle response C#

The scenario is that a mail is sent to an inbox. Attached to the mail is a html file which the user clicks to open the page in a browser. They then click a link on the webpage which opens a PDF file online.
Now, what I want to achieve programmatically with c# is to save the attached html file on disk, open the file, find the link, click it and save the file that opens to disk.
I have gotten as far as programmatically open the email and save the attached html file to disk. But now I'm sort of stuck at opening the file programmatically.
I've gotten as far as creating a FileWebRequest to open the file but I don't know how to find the link ("a" tag, only on in the whole page) and programmatically click it (in c#) so the PDF opens so I can download it and save to disk.
What needs to be done after the filewebrequest?
FileWebRequest req = (FileWebRequest)WebRequest.Create(pathToHtmlFile);
FileWebResponse res = (FileWebResponse)req.GetResponse();
// What now..?
At first you should extract the PDF URL using RegEx from html content and then download it using WebClient :
private static string FindPdfFileDownloadLink(string htmlContent)
{
return Regex.Match(htmlContent, #"^(https?:\/\/)?www\.([\da-z\.-]+)\.([a-z\.]{2,6})\/[\w \.-]+?\.pdf$").Value;
}
public static int Main(string[] args)
{
string htmlContent = File.ReadAllText("1.html");
string pdfUrl = FindPdfFileDownloadLink(htmlContent);
using (WebClient wClient = new WebClient())
{
wClient.DownloadFile(pdfUrl, #"1.pdf");
}
Console.Read();
return 0;
}
if you want to really click on link for any reason you can load the html in a hidden web browser and find the element that you want and click on it.
To load the content into WebBrowser control :
webBrowser1.Navigate(#"1.html");
and to find and click on element :
HtmlElement link = webBrowser.Document.GetElementByID("link_id_58547")
link.InvokeMember("Click")

Replicate Webbrowser Save Page As function in C#

I'm looking for a method that replicates a Web Browsers Save Page As function (Save as Type = Text Files) in C#.
Dilemma: I've attempted to use WebClient and HttpWebRequest to download all Text from a Web Page. Both methods only return the HTML of the web page which does not include dynamic content.
Sample code:
string url = #"https://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=" + package.Item2 + "&LOCALE=en";
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
string content = client.DownloadString(url);
}
}
The above example returns the HTML without the tracking events from the page.
When I display the page in Firefox, right click on the page and select Save Page As and save as Text File all of the raw text is saved in the file. I would like to mimic this feature.
If you are scraping a web page that shows dynamic content then you basically have 2 options:
Use something to render the page first. The simplest in C# would be to have a WebBrowser control, and listen for the DocumentCompleted event. Note that there is some nuance to this when it fires for multiple documents on one page
Figure out what service the page is calling to get the extra data, and see if you can access that directly. It may well be the case that the Canadapost website is accessing an API that you can also call directly.

Download webpage with JavaScript by webpage c#

I want to download a webpage after or with his JavaScript. For example a webpage with data that load in javaScript. I'm using WebClient class.
My code:
WebClient wb = new WebClient();
htmlDoc = wb.DownloadString(link);
My problem is that I get the html code before the data is downloaded by the javaScript.
What can I do?
Here is my link: http://www.select-test.com/HTML/frmDisplayGrid.aspx?Type=cat&Data=OS
thanks,
Chani

Open Image from IsolatedStoreage?

I want to open an Image from the IsolatedStorage?
The image was downloaded before and correctly written (I checked that with the Isolated Storage Explorer).
When I try to open the Image with BitmapImage(uriInIsolatedStorage) and set that as source for a Silverlight Image Control it crashs when I listen to the image failed event.
The exception said "AG_E_NETWORK_ERROR"
Does anyone has an idea?
Uri imageSource = new Uri("/cover.jpg", UriKind.Relative);
BitmapImage bi = new BitmapImage(imageSource);
bi.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(MainPage_ImageFailed);
bi.ImageOpened +=new EventHandler<RoutedEventArgs>(bi_ImageOpened);
imageCtrl.Source = bi;
Unfortunately you cannot load an image directly from isolated storage via URI. You have to open the file and do some more steps as described here or (a bit easier) here.
It boils down to:
creating an IsolatedStorageFileStream for your image
creating a BitmapImage from file data
setting BitmapImage as Image source
There is also an isostore: URI scheme but it doesn't work.

Categories

Resources