How to download multiple files using webclient ?

Chocolade 536 Reputation points
2022-08-28T17:33:34.937+00:00

one single file is fine but when i loop over the List of links it's saving to the hard disk many empty files.

private void btnGetDownload_Click(object sender, EventArgs e)  
        {  
            for (int i = 0; i < videosLinks.Count; i++)  
            {  
                string fileName = System.IO.Path.GetFileName(videosLinks[i]);  
                DownloadFile(videosLinks[i], @"D:\Videos\videos\" + fileName);  
            }  
        }  
  
        public void DownloadFile(string urlAddress, string location)  
        {  
            Stopwatch sw = new Stopwatch();  
            using (WebClient webClient = new WebClient())  
            {  
                webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");  
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => Completed(sender, e, sw));  
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));  
                Uri URL = new Uri(urlAddress);  
                sw.Start();  
                try  
                {  
                    webClient.DownloadFileAsync(URL, location);  
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.Message);  
                }  
            }  
        }  
  
        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)  
        {  
            progressBar1.Value = e.ProgressPercentage;  
            lblFileName.Text = string.Format("data", string.Format("{0} / {1} MB",  
               (e.BytesReceived / 1024d / 1024d).ToString("0.00"),  
               (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00")));  
            btnGetDownload.Text =  "Downloading...";  
            label1.Text =  string.Format("{0} Kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));  
        }  
  
        private void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw)  
        {  
            if (e.Cancelled == true)  
            {  
                btnGetDownload.Text =  "Fails.";  
                sw.Stop();  
            }  
            else  
            {  
                btnGetDownload.Text =  "Finish.";  
                label1.Text = "0 Kb/s";  
                sw.Stop();  
            }  
        }  

If i'm doing in the button click event without a loop just :

 string fileName = System.IO.Path.GetFileName(videosLinks[0]);  
 DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);  

this will work fine but i want to download each file one by one from the List videosLinks.

i tried to search and use httpclient and async await but could not fine a complete project and what i tried so far didn't work at all. not sure how to use the results i found mostly in stackoverflow site that's why i'm using webclient. the problem is how to download all the files in the list one by one ?

Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Chocolade 536 Reputation points
    2022-08-28T18:16:16.707+00:00

    This is working fine :

    private void btnGetDownload_Click(object sender, EventArgs e)  
            {  
                string fileName = System.IO.Path.GetFileName(videosLinks[0]);  
                DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);  
            }  
      
            public void DownloadFile(string urlAddress, string location)  
            {  
                Stopwatch sw = new Stopwatch();  
                using (WebClient webClient = new WebClient())  
                {  
                    webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");  
                    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => Completed(sender, e, sw));  
                    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));  
                    Uri URL = new Uri(urlAddress);  
                    sw.Start();  
                    try  
                    {  
                        webClient.DownloadFileAsync(URL, location);  
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.Message);  
                    }  
                }  
            }  
      
            private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)  
            {  
                progressBar1.Value = e.ProgressPercentage;  
                lblFileName.Text = string.Format("data", string.Format("{0} / {1} MB",  
                   (e.BytesReceived / 1024d / 1024d).ToString("0.00"),  
                   (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00")));  
                btnGetDownload.Text =  "Downloading...";  
                label1.Text =  string.Format("{0} Kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));  
            }  
      
            private void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw)  
            {  
                if (e.Cancelled == true)  
                {  
                    btnGetDownload.Text =  "Fails.";  
                    sw.Stop();  
                }  
                else  
                {  
                    btnGetDownload.Text =  "Finish.";  
                    label1.Text = "0 Kb/s";  
                    sw.Stop();  
      
                    if (videosLinks.Count > 0)  
                    {  
                        videosLinks.RemoveAt(0);  
                        string fileName = System.IO.Path.GetFileName(videosLinks[0]);  
                        DownloadFile(videosLinks[0], @"D:\Videos\videos\" + fileName);  
                    }  
                }  
            }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.