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";
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
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.