8

I'm using WebBrowser control to navigate through a login page and download a file. Since I can't find a way to manage the download automatically with the control I'm using the WebClient class to try and achieve this.

Problem is that since the WebClient isn't in the same context/session as the browser all i'm downloading is the Security Error screen.

Any ideas on how I can pass the context of the WebBrowser session to the WebClient?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
g.foley
  • 2,152
  • 3
  • 19
  • 27
  • A late answer for future references: `URLDownloadToCacheFile` [can be used for this](http://stackoverflow.com/a/19025793/1768303). – noseratio Sep 26 '13 at 10:47

2 Answers2

13

After one week googling a trying for a solution I found one that is so simple!

I you what to silently download a file in an HTTPS URL and a webbrowser control just do this.

1) Log in using the webbrowser 2) use this code to download.

//build de URL 

  string _url = "https://........."

  //define a download file name and location

  string _filename = @"C:\Users\John\Documents\somefile.pdf";

  //create a webcliente

  WebClient cliente = new WebClient();

  //do some magic here (pass the webbrowser cokies to the webclient)

  cliente.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);

  //and just download the file

  cliente.DownloadFile(_urlpdf, _filename);

It solved my problem

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
Petrus246
  • 131
  • 2
  • 4
4

It should be simply a matter of emulating the cookies and headers in the WebBrowser session and re-using them to impersonate the session in WebClient, but it looks like you're already hot on that path.

Here's how I'd proceed.

  1. Get cookies and headers from WebBrowser.

    Cookies: You can get the cookies from your WebBrowser session by handling the DocumentCompleted event of the WebBrowser control and parsing the cookie set from DocumentCompleted event.

    Headers: Use a proxy like Fiddler [www.fiddler2.com/] to read the headers so you'll know what's required by the server.

  2. Utilize identity collected above for WebClient.

    Headers: Iterate through all your collected headers and be sure they are added to the webclient using myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); for example

    Cookies: See this post.

Community
  • 1
  • 1
Laramie
  • 5,457
  • 2
  • 39
  • 46