Download Files from Web in C#
Following example demonstrates how to download files from any website to local disk. By using WebClient class and associated method DownloadFile we can download file.
Parameters of this method are url of the web file and location of local computer.
Synchronous way to download file
WebClient wc = new WebClient();
wc.DownloadFile("http://www.yoursite.com/filename.txt", @"c:\filename.txt"); |
Asynchronous way to download file
private void OnDownload_Click(object sender, EventArgs event)
{
WebClient wc = new WebClient();
//listen to file download completed event
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadCompleted);
//listen to progress state change event
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnProgressChanged);
wc.DownloadFileAsync(new Uri("http://www.yoursite.com/filename.txt"), @"c:\filename.txt");
}
private void OnProgressChanged(object sender, DownloadProgressChangedEventArgs event)
{
myProgressBar.Value = event.ProgressPercentage;
}
private void OnDownloadCompleted(object sender, AsyncDownloadCompletedEventArgs event)
{
MessageBox.Show("Download Finished!!");
} |
Related Posts:
.NET, C#, WebClient
Leave a Reply
You must be logged in to post a comment.