WebClient.DownloadFileAsync - Download files one at a time

前端 未结 3 661
醉梦人生
醉梦人生 2020-12-05 16:42

I am using the code below to download multiple attachments from a TFS server:

foreach (Attachment a in wi.Attachments)
{    
    WebClient wc = new WebClient         


        
3条回答
  •  伪装坚强ぢ
    2020-12-05 17:21

    To simplify the task you can create separated attachment list:

    list = new List(wi.Attachments);
    

    where list is private field with type List. After this you should configure WebClient and start downloading of first file:

    if (list.Count > 0) {
       WebClient wc = new WebClient();
       wc.Credentials = (ICredentials)netCred;
       wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
       wc.DownloadFileAsync(list[0].Uri, @"C:\" + list[0].Name);
    }
    

    Your DownloadFileComplete handler should check if not all files already downloaded and call DownloadFileAsync again:

    void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
       // ... do something useful 
       list.RemoveAt(0);
       if (list.Count > 0)
          wc.DownloadFileAsync(list[0].Uri, @"C:\" + list[0].Name);
    }
    

    This code is not optimized solution. This is just idea.

提交回复
热议问题