Want to Learn Javascript.

How to Download a File in C#

4. August 2010 13:32 by Scott in   //  Tags:   //   Comments (0)

The first example shows how to download a file synchronously and the second, asynchronously.  Just a quick post.  Thought it would help someone out that.

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://yahoo.com/file.txt", @"c:\file.txt");

This one shows how to download a file in C# asynchronously.

private void btnDownload_Click(object sender, EventArgs e)
{
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}
If you liked this post, please be sure to subscribe to my RSS Feed.