Dec 30

File Downloading in C# Applications

For ASP.Net web form applications, you can use [for file download]

Synchronously


using System.Net;

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

or

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!");
}

--
Another Simple Approach : When you are using Ajax or Web-Service in Ajax style (.asmx), this will be handy though will expose the file path. For publicly open applications use it with care and take required security pre-cautions.

use the regular anchor tag with download attribute.


Skip to toolbar