Click here to Skip to main content
15,888,803 members
Articles / Programming Languages / Visual Basic

Downloading Files in .NET With All Information: Progressbar, Download Speed, Supports Cancel and Resume

,
Rate me:
Please Sign up or sign in to vote.
4.56/5 (43 votes)
22 Apr 2009CPOL2 min read 417.3K   29.5K   188   99
How to download files in .NET with all information about the progess (progressbar, download speed), supports cancel and resume
Screenshot - screen.jpg

Introduction  

I'll explain how you can build a complete, reliable and powerful download manager with .NET Framework.
It is able to show a rarity of data about the download in progress, including the download speed, the file size, the downloaded size, and the percentage of completion.

A completely new class has been written based on this code, which features logic/layout abstraction, multiple file download support, and is more easy to use by providing a variety of properties and events. Check out the FileDownloader article.

The files are downloaded via the HttpWebRequest  and HttpWebResponse, and written to a file with the StreamWriter. All this is done on a separate thread (with a BackgroundWorker), so the application using this downloader won't freeze.

Using the Code 

The demo application is pretty simple, and contains only the needed UI components for downloading a file. You can of course implement this downloader in your own application, or just use it to download in the background without any user interaction.

The most important code can be found in the DoWork method of the BackgroundWorker. First, an attempt will be made to establish a connection to the file. If this is successful, a script in the Do loop will start downloading the file block by block, until there are no remaining bytes to be downloaded. Note that as soon as a block of data has been received, it's written to the local target file.

VB.NET
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, _
    ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        'Creating the request and getting the response
        Dim theResponse As HttpWebResponse
        Dim theRequest As HttpWebRequest
        Try 'Checks if the file exist

            theRequest = WebRequest.Create(Me.txtFileName.Text)
            theResponse = theRequest.GetResponse
        Catch ex As Exception

            MessageBox.Show("An error occurred while downloading file. _
			Possible causes:" & ControlChars.CrLf & _
                            "1) File doesn't exist" & ControlChars.CrLf & _
                            "2) Remote server error", "Error", _
			MessageBoxButtons.OK, MessageBoxIcon.Error)

            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)

            Me.Invoke(cancelDelegate, True)

            Exit Sub
        End Try
        Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)

        Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
        Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate

        Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)

        'Replacement for Stream.Position (webResponse stream doesn't support seek)
        Dim nRead As Integer

        'To calculate the download speed
        Dim speedtimer As New Stopwatch
        Dim currentspeed As Double = -1
        Dim readings As Integer = 0

        Do

            If BackgroundWorker1.CancellationPending Then 'If user aborts download
                Exit Do
            End If

            speedtimer.Start()

            Dim readBytes(4095) As Byte
            Dim bytesread As Integer = theResponse.GetResponseStream.Read_
						(readBytes, 0, 4096)

            nRead += bytesread
            Dim percent As Short = (nRead * 100) / length

            Me.Invoke(safedelegate, length, nRead, percent, currentspeed)

            If bytesread = 0 Then Exit Do

            writeStream.Write(readBytes, 0, bytesread)

            speedtimer.Stop()

            readings += 1
            If readings >= 5 Then 'For increase precision, _
			' the speed is calculated only every five cycles
                currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
                speedtimer.Reset()
                readings = 0
            End If
        Loop

        'Close the streams
        theResponse.GetResponseStream.Close()
        writeStream.Close()

        If Me.BackgroundWorker1.CancellationPending Then

            IO.File.Delete(Me.whereToSave)

            Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)

            Me.Invoke(cancelDelegate, True)

            Exit Sub

        End If

        Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)

        Me.Invoke(completeDelegate, False)

End Sub

This code uses delegates to invoke methods on the main thread, and pass data about the download progress to them. 

The code does not support FTP downloads, but can be easily modified to do this.  

Resume Downloads 

It is possible to modify the code to allow resuming downloads. Add this code before the first use of the HttpWebRequest object.

VB.NET
theRequest.AddRange(whereYouWantToStart) '<- add this

You'll also need to set the Position property of the FileStream instance to the position where you want to resume the download. So be sure you also save this before the download is cancelled.

VB.NET
Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Open)
writeStream.Position = whereYouWantToStart

Calculating Speed 

The code contains built in download speed calculation, using the StopWatch class. This will return another result every time 5 packages have been downloaded. Note that you can also manually calculate the speed, and use a timer to get data at a more regular interval.

License

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


Written By
Software Developer
Belgium Belgium
I am a free and open source software enthusiast and freelance software developer with multiple years of experience in both web and desktop development. Currently my primarily focus is on MediaWiki and Semantic MediaWiki work. I'm in the all time top 10 MediaWiki comitters and am one of the WikiWorks consultants. You can contact me at jeroendedauw at gmail for development jobs and questions related to my work.

More info can be found on my website [0] and my blog [1]. You can also follow me on twitter [2] and identi.ca [3].

[0] http://www.jeroendedauw.com/
[1] http://blog.bn2vs.com/
[2] https://twitter.com/#!/JeroenDeDauw
[3] http://identi.ca/jeroendedauw

Written By
Student
Italy Italy
I'm a young Italian student from Milan.
I usually develop in Visual Basic.Net (and also C#), both Windows and Web (ASP.Net) applications.
Moreover I also know some other programming languages: PHP, HTML, SQL, VB6 and Javascript. (and a bit of C++).
All of my programming projects can be found on my website: www.thetotalsite.it.

Comments and Discussions

 
GeneralRe: Permission to use this code Pin
Carmine_XX22-Apr-09 6:26
Carmine_XX22-Apr-09 6:26 
GeneralRe: Permission to use this code Pin
Jeroen De Dauw23-Apr-09 2:08
Jeroen De Dauw23-Apr-09 2:08 
GeneralRe: Permission to use this code Pin
Carmine_XX23-Apr-09 2:31
Carmine_XX23-Apr-09 2:31 
Generalhaving trouble downloading files that are 1.5gb's or greater Pin
lord_snow5-Mar-09 22:15
lord_snow5-Mar-09 22:15 
GeneralRe: having trouble downloading files that are 1.5gb's or greater Pin
driven6421-Apr-09 17:22
driven6421-Apr-09 17:22 
GeneralI am getting access denied after making some changes Pin
d0gesty1e26-Jan-09 7:19
d0gesty1e26-Jan-09 7:19 
GeneralRe: I am getting access denied after making some changes Pin
georec9-Feb-09 11:29
georec9-Feb-09 11:29 
Questionhow to pause download and resume? Pin
ramakoteswarrao.p7-Nov-08 0:36
ramakoteswarrao.p7-Nov-08 0:36 
AnswerI hope it will give your solution for resuming download Pin
Аslam Iqbal25-Jan-09 22:11
professionalАslam Iqbal25-Jan-09 22:11 
QuestionWhat if your file isn't there, and you want it to go to the next? Pin
navyjax221-Oct-08 12:23
navyjax221-Oct-08 12:23 
AnswerRe: What if your file isn't there, and you want it to go to the next? - Solved [modified] Pin
navyjax221-Oct-08 13:07
navyjax221-Oct-08 13:07 
QuestionPlease how to pause download and resume? Pin
anass20085-Sep-08 1:52
anass20085-Sep-08 1:52 
QuestionI have a question Pin
evilson30-Jul-08 1:15
evilson30-Jul-08 1:15 
AnswerRe: I have a question Pin
Carmine_XX30-Jul-08 1:44
Carmine_XX30-Jul-08 1:44 
GeneralThanks for the great work! Pin
MAP Tiger4-Jul-08 21:10
MAP Tiger4-Jul-08 21:10 
GeneralNo contentlength when downloading html Pin
ArComAr14-Jun-08 10:49
ArComAr14-Jun-08 10:49 
GeneralNeed same project without http Pin
jm157611-Apr-08 5:18
jm157611-Apr-08 5:18 
GeneralRe: Need same project without http Pin
Carmine_XX11-Apr-08 5:22
Carmine_XX11-Apr-08 5:22 
Questionhow to download multiple files in dotnet Pin
jayas7-Apr-08 2:13
jayas7-Apr-08 2:13 
AnswerRe: how to download multiple files in dotnet Pin
Carmine_XX11-Apr-08 5:26
Carmine_XX11-Apr-08 5:26 
Generaldownload and Login to rapidshare.com Pin
Michalss4-Jan-08 14:02
Michalss4-Jan-08 14:02 
GeneralRe: download and Login to rapidshare.com Pin
Carmine_XX4-Jan-08 14:37
Carmine_XX4-Jan-08 14:37 
GeneralRe: download and Login to rapidshare.com Pin
Koshenoo28-Aug-08 1:23
Koshenoo28-Aug-08 1:23 
GeneralHttpWebResponse,HttpWebRequest in loop : loop second round can't get the file length Pin
ToGo41316-Nov-07 6:42
ToGo41316-Nov-07 6:42 
GeneralMindblowing.... Pin
Paresh Rathod23-Oct-07 20:29
Paresh Rathod23-Oct-07 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.