我正在使用带有 CookieContainer 的 Webclient 从 Web 服务(Sharepoint)下载数据。
我想 DownloadDataAsync 以便下载多个文档并在每个文档下载时更新一个进度条。非异步版本 - DownloadData 不发送进度更新。
- 在继续下一个文档之前,如何让异步版本在 doc.BinaryData = xx 行等待?
- 如何从 DownloadFileCompleted 事件中获取字节数组?
如何在不使用 DoEvents 的情况下将更改应用到进度条?
部分类 Form() { void Main() { List urls= new List(); //urls.Add("xxxxxxx"); //从某个地方获取它们
for (int i = 0; i < urls.Count; i++) { var doc = new Document(); doc.BinaryData = DocumentAsArray(urls.ElementAt(i)); entities.AddToDocument(doc); } } public byte[] DocumentAsArray(string URL) { byte[] @return = null; using (CookieAwareWebClient client = new CookieAwareWebClient()) { client.CookieContainer = spAuthentication.CookieContainer; // Assign the events to capture the progress percentage client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadDataAsync(new Uri(URL)); } return @return; } void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBarControlFile.Position = e.ProgressPercentage; var newPc = string.Format("Downloaded {0} %", e.ProgressPercentage); labelControlFile.Text = newPc; Application.DoEvents(); } void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { progressBarControlFile.Position = progressBarControlFile.Properties.Maximum; labelControlFile.Text = string.Format("{0} %", progressBarControlFile.Properties.Maximum); Application.DoEvents(); }
}
公共类 CookieAwareWebClient : WebClient { 公共 CookieContainer CookieContainer { 获取;放; }
protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); var webRequest = request as HttpWebRequest; if (webRequest != null) { webRequest.CookieContainer = this.CookieContainer; webRequest.KeepAlive = false; } return request; }
} }