Download a file from the Internet to a local progress bar file in C #

I have a small application that downloads some files from a remote (HTTP) server to the user's local hard drive, some of the files are large, but I don’t know how large they are at runtime. Is there any method that will allow me to upload a file with some type of progress bar?

This is a WinForms application, I am currently using WebClient.DownloadFile () to upload a file.

Edit: I looked at the DownloadProgressChanged and OnDownloadProgressChanged events, and they seem to work fine, but they won't work for my solution. I upload several files, and if I use WebClient.DownloadFileAsync, then the event is fired several times per second, because each file calls it.
Here is the basic structure of the application:

  • Download a list of files, usually around 114
  • Run a loop over the list of files and load each one in its absence

I am not opposed to downloading each file separately, but without downloading it using DownloadFileAsync () I cannot use event handlers.

+3
source share
4 answers
+2

, , .

In addition, in the ProgressChanged event, you have the TotalBytesToReceive property and the BytesReceived property.

private void StartDownload()
{

    // Create a new WebClient instance.
    WebClient myWebClient = new WebClient();

    // Set the progress bar max to 100 for 100%
    progressBar1.Value = 0;
    progressBar1.Maximum = 100;

    // Assign the events to capture the progress percentage
    myWebClient.DownloadDataCompleted+=new DownloadDataCompletedEventHandler(myWebClient_DownloadDataCompleted);
    myWebClient.DownloadProgressChanged+=new DownloadProgressChangedEventHandler(myWebClient_DownloadProgressChanged);

    // Set the Uri to the file you wish to download and fire it off Async
    Uri uri = new Uri("http://external.ivirtualdocket.com/update.cab");
    myWebClient.DownloadFileAsync(uri, "C:\\Update.cab");

}

void myWebClient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

void myWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    progressBar1.Value = progressBar1.Maximum;
}
+1
source

I needed to solve a similar problem, and the GenericTypeTea sample code did the trick; except that I found that the DownloadDataCompleted event does not fire when the DownloadFileAsync method is called. Instead, the DownloadFileCompleted event occurs.

+1
source

Source: https://habr.com/ru/post/1712279/


All Articles