65.9K
CodeProject is changing. Read more.
Home

Download File Using C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (15 votes)

May 30, 2012

CPOL
viewsIcon

210615

Download file using C#.

Introduction

This article describes code to download a file using C#...

Background

While browsing forums today I came across a question which asked for a solution to download a file from a web server programmatically. The solution is very simple and below is the code which achieves the goal. Here I am downloading a file asynchronously on Button Click.

Using the code

private void buttonDownloadFile_Click(object sender, EventArgs e)
{
    string url = @"http://www.thereforesystems.com/wp-content/uploads/2008/08/image35.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\image35.png");
 }

void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show("File downloaded");
}

You can also download the file synchronously using WebClient.DownloadFile() method.