5,699,431 members and growing! (23,886 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Internet     Intermediate License: The Code Project Open License (CPOL)

An easy-to-use URL file downloader class for .NET

By Scott Dorman

A simple to use resumable file downloader class that provides progress feedback for .NET 2.0 or .NET 1.1
VB, C# 1.0, C# 2.0, C#Windows, .NET, .NET 1.1, .NET 2.0, NT4, Win2K, WinXP, Win2003, Vista, Mono, DotGNUVS.NET2003, VS2005, Visual Studio, Dev

Posted: 25 Aug 2006
Updated: 17 Aug 2007
Views: 73,109
Bookmarked: 125 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
20 votes for this Article.
Popularity: 5.88 Rating: 4.52 out of 5
1 vote, 5.0%
1
0 votes, 0.0%
2
1 vote, 5.0%
3
2 votes, 10.0%
4
16 votes, 80.0%
5

Introduction

For one of my projects at work, I needed the ability to download a file from a given URL. Unfortunately, the methods provided by the WebClient class don't do anything more than download the data. I needed something that gave the ability to provide progress feedback and that was resumable.

As I started my searches on the web for any existing code, I came across two articles on CodeProject that helped get me very close to what I needed. The first article was by John Batte, while the second article by Phil Crosby was a derivation of his work. Using both of these articles as a starting point, I was able to make another derivation that accomplished my goals.

The code samples and content of this article are focused on the .NET 2.0 implementation and any code updates have been made only to that version. The .NET 1.1 implementation is provided for backwards compatibility only and I have no further plans to continue making changes to it.

Using the Code

The FileDownloader class is the main class and is very simple to use. The minimal implementation is:

private void DoDownload()
{
    FileDownloader downloader = new FileDownloader();
    downloader.Download(new Uri("http://www.codeproject.com" +
        "/info/stuff/cp_bg_black1024.gif"), @"C:\Temp");
}

This creates a new instance of the FileDownloader class and downloads the file located at "http://www.codeproject.com/info/stuff/cp_bg_black1024.gif" to the "C:\Temp" folder.

FileDownloader actually performs all download operations asynchronously. When the FileDownloader.Download(Uri url, string destinationFolder) method is called, it accomplishes a synchronous download by waiting until a signal is set indicating that the download has completed. This allows for both synchronous downloads -- through the use of the Download methods -- or asynchronous downloads, through the use of the DownloadAsync methods. Both the synchronous and asynchronous methods ultimately call the same internal method to perform the actual download.

This internal method, called DownloadAsyncCore, instantiates an instance of the DownloadInfo internal class. This class is similar in nature to the FileInfo class provided by the .NET CLR and provides FileDownloader with all of the information required to actually download the file. This includes:

  • The length of the file being downloaded, if known
  • The Stream that is being used to actually download the file
  • The WebResponse that is servicing the request

Once the DownloadInfo class is instantiated, the data is downloaded in 1KB chunks and written to the disk. This is the default block size and can be changed through the BlockSize property. It is this implementation that allows the download to resume if it is cancelled or interrupted.

While this implementation is functional, it does prevent anyone from using the class who is behind a proxy or who requires authentication to access the requested URL. In order to support these scenarios, the FileDownloader class provides both a Proxy property that accepts an IWebProxy derived object and a Credentials property that accepts an ICredentials derived object. These properties are also passed on to the underlying DownloadInfo object.

Finally, the events provide progress feedback. The WebClient class in .NET 2.0 has asynchronous download methods that provide just such events. These methods are serviced by the DownloadCompletedEventArgs and DownloadProgressChangedEventArgs EventArgs derived classes. Unfortunately, both of these classes have internal constructors and are new in .NET 2.0, so I wasn't able to make use of them. Instead, I created a new triplet set of EventArgs derived classes to handle the three events that are exposed by the FileDownloader class. These events are:

  • public event EventHandler<FileDownloadCompletedEventArgs> DownloadCompleted
  • public event EventHandler<FileDownloadProgressChangedEventArgs> DownloadProgressChanged;
  • public event EventHandler<FileDownloadStatusChangedEventArgs> DownloadStatusChanged;

These events are raised during the actual file download to provide the caller with status information (DownloadStatusChanged), progress information (DownloadProgressChanged) and completion information (DownloadCompleted). A complete example looks like this:

private void DoDownload()
{
    Uri fileUrl = new Uri("http://www.codeproject.com" +
        "/info/stuff/cp_bg_black1024.gif");
    string tempPath = Path.GetTempPath();
    string fileName = Path.GetFileName(fileUrl.AbsoluteUri);
    string downloadPath = Path.Combine(tempPath, fileName);

    FileDownloader downloader = new FileDownloader();
    downloader.Proxy = WebRequest.DefaultWebProxy;
    downloader.Credentials = CredentialCache.DefaultCredentials;

    downloader.DownloadCompleted += new
        EventHandler<FileDownloadCompletedEventArgs>(OnDownloadCompleted);
    downloader.DownloadProgressChanged += new
        EventHandler<FileDownloadProgressChangedEventArgs>(
        OnDownloadProgressChanged);
    downloader.DownloadStatusChanged += new
        EventHandler<FileDownloadStatusChangedEventArgs>(
        OnDownloadStatusChanged);

    // Download the requested file to the specified folder

    downloader.Download(fileUrl, tempPath);
}

private void OnDownloadCompleted(object sender,
    FileDownloadCompletedEventArgs e)
{
    // Do something when the download completes.

}

private void OnDownloadProgressChanged(object sender,
    FileDownloadProgressChangedEventArgs e)
{
    // Do something when the progress changes,

    // usually you would increment a progress bar.

}

private void OnDownloadStatusChanged(object sender,
    FileDownloadStatusChangedEventArgs e)
{
    // Do something when that status changes.

}

Here is the same example using VB.NET. This example is based on the comment [^] by CBlackburn [^].

Private Sub DoDownload()
    Dim fileUrl As Uri = New Uri("http://www.codeproject.com/" & _
        "info/stuff/cp_bg_black1024.gif")

    Dim tempPath As String = Path.GetTempPath()
    Dim fileName As String = Path.GetFileName(fileUrl.AbsoluteUri)
    Dim downloadPath As String = Path.Combine(tempPath, fileName)

    Dim downloader As FileDownloader = New FileDownloader()
    downloader.Proxy = WebRequest.DefaultWebProxy
    downloader.Credentials = CredentialCache.DefaultCredentials

    AddHandler downloader.DownloadCompleted, _
        AddressOf OnDownloadCompleted
    AddHandler downloader.DownloadProgressChanged, _
        AddressOf OnDownloadProgressChanged
    AddHandler downloader.DownloadStatusChanged, _
        AddressOf OnDownloadStatusChanged

    downloader.Download(fileUrl, tempPath)
End Sub

Private Sub OnDownloadCompleted(ByVal sender As Object, _
    ByVal e As FileDownloadCompletedEventArgs)
    ' Do something when the download completes.

End Sub

Private Sub OnDownloadProgressChanged(ByVal sender As Object, _
    ByVal e As FileDownloadProgressChangedEventArgs)
    ' Do something when the progress changes,

    ' usually you would increment a progress bar.

End Sub

Private Sub OnDownloadStatusChanged(ByVal sender As Object, _
    ByVal e As FileDownloadStatusChangedEventArgs)
    ' Do something when that status changes.

End Sub

The complete public API for the FileDownloader class is available in the documentation CHM file that is part of the download.

Points of Interest

While the FileDownloader class is available as both a .NET 2.0 and .NET 1.1 solution, only the .NET 2.0 solution has been updated to provide the asynchronous download features and other modifications listed in the revision history.

The DownloadInfo class implements the IDisposable pattern. However, the way this pattern is implemented may be different than many of you have seen before. For more information, please refer to this article: Implementing IDisposable and the Dispose Pattern Properly [^] .

Revision History

16-August-2007:

  • Added the ability to set the User-agent HTTP header.

12-August-2007:

  • Added asynchronous support
  • Added the ability to retrieve the last modified date of the file
  • Added support for Pre-Authenticating the web request
  • Added the ability to download an HTML page
  • Added the ability to overwrite the file downloaded if it already exists

11-January-2007:

  • Added a complete example in VB.NET

27-August-2006:

  • Updated source code to include an application configuration file

25-August-2006:

  • Original article

License

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

About the Author

Scott Dorman


Mvp
Scott is a C# MVP and has been involved with computers in one way or another for as long as he can remember, but started professionally in 1993. After spending 6 years as a systems administrator, Scott branched out and started developing eCommerce store fronts. From there, he has worked on many different projects and has been working with .NET and C# since 2001.

He has worked at Fortune 500 companies and privately held start-ups focused on IT consulting where he gained experience in embedded systems design and software development to systems administration and database programming, and everything in between.

Although his primary focus right now is commercial software applications using Microsoft .NET technologies, he prefers building infrastructure components, reusable shared libraries and helping companies define, develop and automate process standards and guidelines.

Scott is currently working as a senior developer and architect on the Gulf coast of Florida, where he lives with his three cats.
Occupation: Software Developer (Senior)
Location: United States United States

Other popular Internet / Network articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 73 (Total in Forum: 73) (Refresh)FirstPrevNext
GeneralGood OnemembersathishC520:38 6 Apr '08  
General[Message Deleted]memberbabaa12:41 27 Feb '08  
GeneralRe: Broken LinkmvpScott Dorman12:47 27 Feb '08  
QuestionCancel a download??memberMarkGMcM18:14 3 Dec '07  
GeneralRe: Cancel a download??memberScott Dorman4:51 30 Dec '07  
GeneralRe: Cancel a download??memberAlex Poon18:22 12 Mar '08  
GeneralRe: Cancel a download??mvpScott Dorman19:17 12 Mar '08  
AnswerRe: Cancel a download?? [modified]membersrtravis13:51 1 Apr '08  
GeneralRe: Cancel a download??mvpScott Dorman15:07 1 Apr '08  
QuestionDownload speedmemberYuriy Opryshko8:04 30 Oct '07  
GeneralRe: Download speedmemberScott Dorman4:50 30 Dec '07  
GeneralUsing in ASP.net Web Apps.memberkirubasankar11:21 21 Sep '07  
GeneralRe: Using in ASP.net Web Apps.memberScott Dorman15:54 22 Oct '07  
QuestionSQL Server integration?memberSAinCA15:10 20 Aug '07  
AnswerRe: SQL Server integration?memberScott Dorman16:01 20 Aug '07  
GeneralRe: SQL Server integration?memberSAinCA7:59 21 Aug '07  
GeneralRe: SQL Server integration?memberScott Dorman10:15 21 Aug '07  
GeneralVery nicememberDmitry Khudorozhkov4:42 17 Aug '07  
GeneralRe: Very nicememberScott Dorman4:50 17 Aug '07  
GeneralDownloading Unknown Filesmembertempsh0:06 11 Jul '07  
GeneralRe: Downloading Unknown FilesmemberScott Dorman3:59 11 Jul '07  
GeneralRe: Downloading Unknown FilesmemberThe_Mega_ZZTer5:54 17 Aug '07  
GeneralCopyrightmembercaribiksun2:39 25 Jun '07  
GeneralRe: CopyrightmemberScott Dorman4:14 25 Jun '07  
GeneralRe: Copyrightmembercaribiksun4:43 25 Jun '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Aug 2007
Editor: Genevieve Sovereign
Copyright 2006 by Scott Dorman
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project