How to download a webfile in C#
By FoxLearn 2/17/2025 7:57:21 AM 89
Synchronous File Download
To download a file synchronously, which will block the UI thread, you can use the WebClient.DownloadFile
method.
// Web URL of the file to download string url = "https://www.google.com/images/icons/ui/doodle_plus/logo.png"; // Local file path to save the downloaded file string localPath = "C:/users/desktop/logo.png"; using (var client = new WebClient()) { client.DownloadFile(url, localPath); }
The above code downloads a file from the provided URL and saves it to the local path. Note that the using
statement ensures the WebClient
instance is disposed of properly.
You can also download a file and save it with its original name like this:
private void downloadFile() { string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string url = "https://www.google.com/images/icons/ui/doodle_plus/logo.png"; string filename = getFilename(url); using (var client = new WebClient()) { client.DownloadFile(url, Path.Combine(desktopPath, filename)); } MessageBox.Show("Download completed"); } private string getFilename(string url) { Uri uri = new Uri(url); return Path.GetFileName(uri.LocalPath); }
Asynchronous File Download
To prevent freezing the UI, you should download files asynchronously. This is done using the WebClient.DownloadFileAsync
method.
For example, How to download a file asynchronously while displaying the download progress:
private void downloadFile() { string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string url = "http://feelgrafix.com/data/wallpaper-hd/Wallpaper-HD-11.jpg"; string filename = getFilename(url); using (WebClient wc = new WebClient()) { wc.DownloadProgressChanged += wc_DownloadProgressChanged; wc.DownloadFileCompleted += wc_DownloadFileCompleted; wc.DownloadFileAsync(new Uri(url), Path.Combine(desktopPath, filename)); } } private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { progressBar1.Value = 0; if (e.Cancelled) { MessageBox.Show("Download was cancelled"); return; } if (e.Error != null) { MessageBox.Show("An error occurred while downloading the file"); return; } MessageBox.Show("File downloaded successfully"); }
Showing Download Progress
You can display download progress in a progress bar. The DownloadProgressChanged
event provides information such as the percentage of completion and the number of bytes received.
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Console.WriteLine($"{e.ProgressPercentage}% | {e.BytesReceived} bytes out of {e.TotalBytesToReceive} bytes downloaded."); }
Cancelling an Asynchronous Download
If you need to cancel an ongoing download, you can do so by calling CancelAsync
on the WebClient
instance.
private WebClient client; private void downloadFile() { string url = "https://www.google.com/images/icons/ui/doodle_plus/logo.png"; string localPath = "C:/users/desktop/logo.png"; client = new WebClient(); client.DownloadFileAsync(new Uri(url), localPath); } private void cancelDownload() { client.CancelAsync(); }
To track cancellation, add the DownloadFileCompleted
event handler to check if the download was cancelled:
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { MessageBox.Show("Download cancelled"); } }
By using asynchronous methods, you can prevent freezing the UI, and with WebClient
's built-in event handlers, you can easily track the download’s progress or cancel it if needed.
Additionally, before starting a download, it’s good practice to check if the device has an active internet connection. You can do this by using NetworkInterface.GetIsNetworkAvailable()
:
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { MessageBox.Show("Internet is available, proceed with the download"); } else { MessageBox.Show("No internet connection available"); }
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#