Home > Enterprise >  Why when using webclient to download a file it's not downloading and getting to the completed e
Why when using webclient to download a file it's not downloading and getting to the completed e

Time:10-11

First I tried both :

DownloadProgressChangedEventHandler and AsyncCompletedEventHandler bit it didn't work. Then I tried both :

client.DownloadProgressChanged  = Client_DownloadProgressChanged;
client.DownloadFileCompleted  = Client_DownloadFileCompleted;

This time it's getting right away to the completed event it's not downloading and not updating the progressBar1.

private void Download()
        {
            WebClient client = new WebClient();
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            client.DownloadProgressChanged  = new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted  = new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged  = Client_DownloadProgressChanged;
            client.DownloadFileCompleted  = Client_DownloadFileCompleted;
            client.DownloadFileAsync(new Uri("https://speed.hetzner.de/10GB.bin"), desktop);
        }

        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            label1.Text = "Download Completed";
        }

        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Maximum = (int)e.TotalBytesToReceive / 100;
            progressBar1.Value = (int)e.BytesReceived / 100;
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Maximum = (int)e.TotalBytesToReceive / 100;
            progressBar1.Value = (int)e.BytesReceived / 100;
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Download();
        }

CodePudding user response:

Declare the button1_Click and Download methods are async and add await before client.DownloadFileAsync.

Or you can use the synchronous version client.DownloadFile

  • Related