Click here to Skip to main content
15,899,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi, i'm use this code for my work.

but that code does not download multiple file with DownloadFileAsync

my code is

C#
<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace Ping_Service
{
    public partial class Form1 : Form
    {

        private readonly string Version = "1.1";
        public Form1()
        {
            InitializeComponent();
        }
        WebClient client;
        public string getVersion()
        {
            return Version;
        }
        //Method to Update 
        private void checkForUpdate()
        {
            string URL = "https://tweak-team.ir/";
            string AppName = "PingService.exe";
            string ServerVersion;
            string serverVersionName = "pingservice.txt";
            // i will make take a old app to check if its work :) 

            WebRequest req = WebRequest.Create(URL + serverVersionName);
            WebResponse res = req.GetResponse();
            Stream str = res.GetResponseStream();
            StreamReader tr = new StreamReader(str);
            ServerVersion = tr.ReadLine();


            if (getVersion() != ServerVersion)
            {
                //Update
                WebClient client = new WebClient();
                byte[] appdata = client.DownloadData(URL + AppName);


                MessageBox.Show("Update is Available!", "PingService", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    
                    using (FileStream fs = File.Create(saveFileDialog1.FileName))
                    {
                        fs.Write(appdata, 0, appdata.Length);
                    }
                }
            }
            else
            {
                MessageBox.Show("No Update is Available!", "PingService", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            checkForUpdate();

        }

        private void bunifuThinButton21_Click(object sender, EventArgs e)
        {
            string[] filePaths = Directory.GetFiles(@"C:\test");
            foreach (string filePath in filePaths)
                File.Delete(filePath);



            Thread thread = new Thread(() => {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri("https://pingservice.ir/icon/Server/pingservice-Germany.ovpn"), @"C:\test\pingservice-Germany.ovpn");
                client.DownloadFileAsync(new Uri("https://pingservice.ir/icon/Server/pingservice-Netherland.ovpn"), @"C:\test\pingservice-Netherland.ovpn");
                client.DownloadFileAsync(new Uri("https://pingservice.ir/icon/Server/Ps-Germany-New.ovpn"), @"C:\test\C:\test\Ps-Germany-New.ovpn");

            });
            thread.Start();

        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.BeginInvoke((MethodInvoker)delegate {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 100;
                progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
            });
        }
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.BeginInvoke((MethodInvoker)delegate {
                MessageBox.Show("Download Compelte", "PingService");
            });
        }
    }
}


thanks for helping

What I have tried:

i should download that files, and i need that Progress Bar.
Posted
Updated 16-May-20 22:37pm

1 solution

Two problems here:
1) You call the method that does the work from your Form.Load event handler - when that is called, the form has not been prepared fro display yet, and cannot be visible. So you can;t use a progress bar at all as the user will not be able to see it!
Since WebClient.DownloadData is a blocking method, the form cannot be displayed until after it is completed (and the Form.Shown event is complete).

Even for a single file, you need to move that into a separate thread if you want a progress indicator, and I'd strongly recommend both using a BackgroundWorker Class (System.ComponentModel) | Microsoft Docs[^] instance to do the work (as it provided a Progress reporting methodology) and using WebClient.DownloadDataAsync Method (System.Net) | Microsoft Docs[^] in combination with Sleep to update progress.
You should also kick this off from the Form.Shown event instead of the Form.Load event.

To download multiple files, all you then need is a loop in your BackgroundWorker.DoWork handler to create new WebClients and download the data one after another.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900