Home > Back-end >  How to download files using HttpClient with a ProgressBar?
How to download files using HttpClient with a ProgressBar?

Time:11-24

I created a new class named SiteDownload and added some links to download images:

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

    public class SiteDownload
    {
        public static List<string> Sites()
        {
            List<string> list = new List<string>();

            list.Add("mysite.com/sites/default/files/1231105.gif");
            list.Add("mysite.com/sites/default/files/1231040.gif");

        return list;
        }

        public static async Task<List<Website>> ParallelDownload(IProgress<ProgressReport> progress, CancellationTokenSource cancellationTokenSource)
        {
            List<string> sites = Sites();
            List<Website> list = new List<Website>();
            ProgressReport progressReport = new ProgressReport();
            ParallelOptions parallelOptions = new ParallelOptions();
            parallelOptions.MaxDegreeOfParallelism = 8;
            parallelOptions.CancellationToken = cancellationTokenSource.Token;
            await Task.Run(() =>
            {
                try
                {
                    Parallel.ForEach<string>(sites, parallelOptions, (site) =>
                    {
                        Website results = Download(site);
                        list.Add(results);
                        progressReport.SitesDownloaded = list;
                        progressReport.PercentageComplete = (list.Count * 100) / sites.Count;
                        progress.Report(progressReport);
                        parallelOptions.CancellationToken.ThrowIfCancellationRequested();
                    });
                }
                catch (OperationCanceledException ex)
                {
                    throw ex;
                }
            });

            return list;
        }

        private static Website Download(string url)
        {
            Website website = new Website();
            WebClient client = new WebClient();
            website.Url = url;
            website.Data = client.DownloadString(url);
            return website;
        }

        public class Website
        {
            public string Url { get; set; }
            public string Data { get; set; }
        }

        public class ProgressReport
        {
            public int PercentageComplete { get; set; }
            public List<Website> SitesDownloaded { get; set; }
        }
    }

in form1:

using System.Linq;
using System.Net;
using System.Threading.Tasks;
using static HttpClientFilesDownloader.SiteDownload;

namespace HttpClientFilesDownloader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void PrintResults(List<Website> results)
        {
            richTextBox1.Text = string.Empty;
            foreach (var item in results)
                richTextBox1.Text  = $"{item.Url} downloaded: {item.Data.Length} characters long.{Environment.NewLine}";
        }

        void ReportProgress(object sender, ProgressReport e)
        {
            progressBar1.Value = e.PercentageComplete;
            label1.Text = $"Completed: {e.PercentageComplete} %";
            PrintResults(e.SitesDownloaded);
        }

        CancellationTokenSource cancellationTokenSource;
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                cancellationTokenSource = new CancellationTokenSource();
                Progress<ProgressReport> progress = new Progress<ProgressReport>();
                progress.ProgressChanged  = ReportProgress;
                var watch = Stopwatch.StartNew();
                var results = await SiteDownload.ParallelDownload(progress, cancellationTokenSource);
                PrintResults(results);
                watch.Stop();
                var elapsed = watch.ElapsedMilliseconds;
                richTextBox1.Text  = $"Total execution time: {elapsed}";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cancellationTokenSource.Dispose();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (cancellationTokenSource != null)
                cancellationTokenSource.Cancel();
        }
    } 
}

The desiger

designer

When I click the START button, nothing happens. I don't see the progressBar get any process and the label1 is not updating and nothing in the RichTextBox. It's just not downloading the images.
I'm not getting any errors, it's just not downloading.

I took this example from this site just instead downloading site/s I'm trying to download images files and save them on the hard disk as images:

ParallelAsync Downloader

  • Related