I am using a Webclient with a CookieContainer to download data from a webservice (Sharepoint).
I want to DownloadDataAsync so that I download multiple documents and update a single Progress Bar for each Document as it downloads. The non async version - DownloadData does not send Progress updates.
- How do I get the Async version to wait at the doc.BinaryData = xx line before moving on the next Document?
- How do I get the byte array from the DownloadFileCompleted event?
How can apply the changes to the progressbar without using DoEvents?
partial class Form() { void Main() { List urls= new List(); //urls.Add("xxxxxxx"); //get them from somewhere
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(); }
}
public class CookieAwareWebClient : WebClient { public CookieContainer CookieContainer { get; set; }
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; }
} }