Download File Asynchronously.

vishalneeraj-24503
Posted by vishalneeraj-24503 under ASP.NET category on | Points: 40 | Views : 511
To download file without blocking the main thread use asynchronous method DownloadFileA­sync.We can also set event handlers to show progress and to detect that the file is downloaded.Below is the code:-

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://anysite.com/file.txt"),@"d:\file.txt");
}

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

private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed.");
}

Comments or Responses

Login to post response