WebBrowser控制会话中的下载文件

我正在使用WebBrowser control来浏览登录页面并下载文件。 由于我无法使用控件自动管理下载,因此我正在使用WebClient类来尝试实现此目的。

问题是,由于WebClient与浏览器不在同一个上下文/会话中,我正在下载的是安全错误屏幕。

关于如何将WebBrowser会话的上下文传递给WebClient任何想法?

它应该只是在WebBrowser会话中模拟cookie和标头并重新使用它们来模拟WebClient中的会话,但看起来你已经在那条路上炙手可热了。

这是我如何进行的。

  1. 从WebBrowser获取cookie和标头。

    Cookie:您可以通过处理WebBrowser控件的DocumentCompleted事件并从DocumentCompleted事件中解析Cookie集,从WebBrowser会话中获取Cookie。

    标题:使用像Fiddler [www.fiddler2.com/]这样的代理来读取标题,这样您就可以知道服务器需要什么。

  2. 利用上面为WebClient收集的身份。

    标题:迭代所有收集的标题,并确保使用myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");将它们添加到web客户 myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); 例如

    Cookies:看这篇文章 。

经过一周的谷歌搜索尝试解决方案后,我发现了一个如此简单!

我是你在HTTPS URL中静默下载文件的方法,而webbrowser控件只是这样做。

1)使用webbrowser登录2)使用此代码下载。

 //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); 

它解决了我的问题