How to download file using C#?

A question which asked for a solution to download a file from a web server programmatically.
The simple solution code is below.

Using below code in button click event:



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

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

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

About the Author

avatar