如果直接用webBrowser.Navigate("http://***.com/");會彈出文件下載的對話框。
而如果用webclient.UploadData()下載,對方網站是asp.net開發的話,postdata中需要有viewstate,也需要登錄。
現在的解決方法是:
1.先使用webbrowser進行網站登錄
2.登錄成功后,把webbrowser中的aspnetSessionID的cookie和DocumentText中的viewstate提取出來,並賦值給webclient
3.使用webclient去下載文件。
下面是第2、3步的代碼
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { Regex reg = new Regex("<input[^<>]*id=\"__VIEWSTATE\"[^<>]*[value=\"\\S+\"]?[^<>]*/>"); Match m = reg.Match(webBrowser1.DocumentText); string viewstate = ""; if (m.Success) { reg = new Regex("value=\"(\\S+)\""); m = reg.Match(m.Value); if (m.Success && m.Groups.Count >= 2) { viewstate = HttpUtility.UrlEncode(m.Groups[1].Value); } } string eventvalidation = ""; reg = new Regex("<input[^<>]*id=\"__EVENTVALIDATION\"[^<>]*[value=\"\\S+\"]?[^<>]*/>"); m = reg.Match(webBrowser1.DocumentText); if (m.Success) { reg = new Regex("value=\"(\\S+)\""); m = reg.Match(m.Value); if (m.Success && m.Groups.Count >= 2) { eventvalidation = HttpUtility.UrlEncode(m.Groups[1].Value); } } string postdata = "EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + viewstate + "&__EVENTVALIDATION=" + eventvalidation; byte[] bytearray = Encoding.UTF8.GetBytes(postdata); WebClient wc = new WebClient(); wc.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie); wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); wc.Headers.Add("ContentLength", bytearray.Length.ToString()); byte[] bs = wc.UploadData(url, "POST", bytearray); string result = Encoding.UTF8.GetString(bs); }
