How to report to a progressbar when downloading files with weblient in a backgroundworker or some how to make that it will not freeze the program ?

sharon glipman 441 Reputation points
2021-10-09T20:56:59.333+00:00

The method for downloading and since it's working for me I want to use it with the progressbar and maybe show more info like each file speed download or how much left to download by size but first the progressbar.

I added to form1 designer a progressBar1 control.

private void ExtractAndDownloadLinks()
        {
            List<string> times = new List<string>();

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
                client.DownloadFile("https://myimages/", @"D:\localfile.html");

                var file = File.ReadAllText(@"D:\localfile.html");

                int idx = file.IndexOf("arrayImageTimes.push");
                int idx1 = file.IndexOf("</script>", idx);

                string results = file.Substring(idx, idx1 - idx);

                var statements = results.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < statements.Length; i++)
                {
                    if (i == 10)
                    {
                        break;
                    }

                    string number = statements[i].Split('\'')[1];

                    times.Add(number); // add to a list instead

                    var link = "https://myimages" + number;

                    Stream stream = client.OpenRead(link);
                    Bitmap bitmap; bitmap = new Bitmap(stream);

                    if (bitmap != null)
                    {
                        bitmap.Save(@"D:\Images\Image" + i + ".gif", ImageFormat.Gif);
                    }

                    stream.Flush();
                    stream.Close();
                }
            }
        }

Calling this method in the init :

public Form1()
        {
            InitializeComponent();

            ExtractAndDownloadLinks();
        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,835 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,279 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,406 Reputation points
    2021-10-09T22:37:53.377+00:00

    You can use the DownloadProgressChanged event handler for WebClient:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
    
        protected override async void OnLoad(EventArgs e) {
            var urls = new[] {
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
                "https://upload.wikimedia.org/wikipedia/commons/d/d4/ESC_large_ISS008_ISS008-E-5604_Trinity_test_site_marked.jpg",
            };
    
            var filenames = new List<string>();
    
            using var wc = new WebClient();
    
            var progressPerUrl = 100 / (float)urls.Length;
    
            for (var i = 0; i < urls.Length; i++) {
                var url = urls[i];
                wc.Headers.Add("User-Agent", "User-Agent: CoolTool/0.0 (https://example.org/cool-tool/; cool-tool@example.org) generic-library/0.0");
    
                var filename = $"out-{i}.jpg";
    
                filenames.Add(filename);
    
                wc.DownloadProgressChanged += (e, sender) => {
                    var urlProgressStart = progressPerUrl * i;
    
                    progressBar1.Value = (int)(urlProgressStart + progressPerUrl * sender.ProgressPercentage / 100f);
                };
    
                await wc.DownloadFileTaskAsync(url, filename);
            }
    
            var saveTasks = new List<Task>();
    
            foreach (var filename in filenames) {
                saveTasks.Add(Task.Run(() => {
                    var newFilename = Path.ChangeExtension(filename, ".gif");
                    Image.FromFile(filename).Save(newFilename, ImageFormat.Gif);
                }));
            }
    
            await Task.WhenAll(saveTasks);
        }
    }
    

    Provided that we know how many items we're downloading beforehand we can work out how far the current file is along the progress bar.


0 additional answers

Sort by: Most helpful