Shayna
Shayna

Reputation: 334

How do I use the progress bar to display the percentage of a download?

I've seen this question asked on other sites but the answers given always caused some sort of exception for me so I'll ask it myself using my own code.

I'm trying to make a program to download a file and display a progress bar while doing so.

My Code So Far

  Private Sub AdwCleanerButton_Click(sender As Object, e As EventArgs) Handles AdwCleanerButton.Click
    My.Computer.Network.DownloadFile(
    "https://www.dropbox.com/s/gg3ocih2dv3t3lg/adwcleaner_6.020.exe?dl=0",
    "C:\Users\llexl\Desktop\adwcleaner_6.020.exe")
End Sub

I'd like to display the percentage of the download onto a progressbar.

Upvotes: 0

Views: 3455

Answers (1)

soohoonigan
soohoonigan

Reputation: 2350

The easiest way to do this with the least amount of code is to use DownloadFile's built-in progress bar, it will show its own small window with a progress bar and cancel button. All you'd have to add to your code is the following parameters:

My.Computer.Network.DownloadFile("https://www.dropbox.com/s/gg3ocih2dv3t3lg/adwcleaner_6.020.exe?dl=0", _
                                 "C:\Users\llexl\Desktop\adwcleaner_6.020.exe", "", "", True, 500, True)

The first True you see after the destination filepath is the parameter that creates a progressbar window.


However, if you want to query the file's total size and get its progress throughout the download to implement your own progress-bar, the process gets a little bit more complicated. You would have to create an event-handler to handle the download's progress-changed event, and then convert the number of bytes received in progress-changed into a percentage and apply that percentage to your progressbar... Then, your download code would look like:

Dim url As String = "https://www.dropbox.com/s/gg3ocih2dv3t3lg/adwcleaner_6.020.exe?dl=0"
Dim savePath As String = "C:\Users\llexl\Desktop\adwcleaner_6.020.exe"
Dim download As New WebClient()
AddHandler download.DownloadProgressChanged, AddressOf Download_ProgressChanged
download.DownloadFileAsync(New Uri(url), savePath)

And your progress-changed handler:

Public Sub Download_ProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)
    Try
        ProgressBar1.Value = CInt(Math.Round((e.BytesReceived / e.TotalBytesToReceive) * 100, 0, MidpointRounding.AwayFromZero))
    Catch ex As Exception
        Debug.Print(ex.ToString)
    End Try
End Sub

But whether or not you can get the file's total size from the downloadprogress object depends on the data that is in the file's head, so there isn't always a number returned from it. You may need to look up an alternate function to use to get the file's size before downloading to use in the progress percent calculation. I believe dropbox has an API that you can use to get that type of information

Upvotes: 3

Related Questions