question

sharonglipman-9594 avatar image
0 Votes"
sharonglipman-9594 asked sharonglipman-9594 commented

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 ?

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();
         }
dotnet-csharpwindows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Paul-5034 avatar image
0 Votes"
Paul-5034 answered sharonglipman-9594 commented

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How can I add to the progressBar1 a percentage symbol % with numbers from 0 to 100 or 1 to 100 ?

0 Votes 0 ·