Download File Programmatically on C#
This article shows how to download a file from website to local disk programmatically on C#. The simple solution is to use WebClient class. There are two behavior of downloading a file: synchronously and asynchronously. Downloading a file synchronously will block main thread until the downloading is finished or any error occur (exception is thrown). On the contrary, downloading a file asynchronously won’t block the main thread. The main thread will continue while the file is being downloaded using thread resources that are automatically allocated from the thread pool.
Download file synchronously
We use DownloadFile method of WebClient class to download file synchronously.
public void DownloadFile(Uri, String) |
The method accepts two parameter which is an URL (as System.Uri) of file to download and the local file name (as String) to save the download to.
Here is the sample code of download a file synchronously
using System.Net; ... private void btnDL_Click(object sender, EventArgs e) { String url = @"http://www.linglom.com/images/Programming/C-Sharp/Download-File/1.png"; // Create an instance of WebClient WebClient webClient = new WebClient(); // Start the download and copy the file to c:\temp webClient.DownloadFile(new Uri(url), @"c:\temp\myfile.png"); } |
Download file asynchronously
We use DownloadFileAsync method of WebClient class to download file asynchronously.
public void DownloadFileAsync(Uri, String) |
The method accepts two parameter which is an URL (as System.Uri) of file to download and the local file name (as String) to save the download to. However, a file is being downloaded in background, we should add event handler to notify when the file download operation completes. To accomplish this, we add DownloadFileCompleted event to the WebClient object.
Here is the sample code of download a file asynchronously
using System.Net; ... private void btnDLASync_Click(object sender, EventArgs e) { String url = @"http://www.linglom.com/images/Programming/C-Sharp/Download-File/1.png"; // Create an instance of WebClient WebClient client = new WebClient(); // Hookup DownloadFileCompleted Event client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); // Start the download and copy the file to c:\temp client.DownloadFileAsync(new Uri(url), @"c:\temp\myfile.png"); } private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { MessageBox.Show("File downloaded"); } |
Sample Source Code
You can download sample project at DownloadFileFromWeb. The source code is written as Windows application using C#, Visual Studio 2010.
wow! lovely, love your tutorial…
well explanatory and straight forward.