WebClient.DownloadFileAsync - Download files one at a time

前端 未结 3 652
醉梦人生
醉梦人生 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<Attachment>(wi.Attachments);
    

    where list is private field with type List<Attachment>. 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.

    0 讨论(0)
  • 2020-12-05 17:21

    At the risk of sounding like an idiot, this worked for me:

    Console.WriteLine("Downloading...");
    client.DownloadFileAsync(new Uri(file.Value), filePath);
    while (client.IsBusy)
    {
        // run some stuff like checking download progress etc
    }
    Console.WriteLine("Done. {0}", filePath);
    

    Where client is an instance of a WebClient object.

    0 讨论(0)
  • 2020-12-05 17:31

    I think that should use Queue

    0 讨论(0)
提交回复
热议问题