Downloading Files from URLs in C#

Downloading files from URLs is a common task in many applications, including web scrapers, file managers, and data analysis tools. In this tutorial, we will explore how to download files from URLs using C#.

Introduction to WebClient

The WebClient class was a popular choice for downloading files from URLs in older versions of .NET. However, it has been deprecated since .NET 6. Despite this, we will cover its usage for completeness and for those working with earlier versions of the framework.

Here’s an example of how to use WebClient to download a file:

using (var client = new WebClient())
{
    client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}

Note that this method is synchronous and will block the calling thread until the download is complete.

For asynchronous downloads with WebClient, you can use the DownloadFileAsync method:

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync(
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}

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

This approach allows you to track the progress of the download and update a UI element, such as a progress bar.

Using HttpClient

The recommended way to download files from URLs in modern .NET applications is by using the HttpClient class. Here’s an example:

using (var client = new HttpClient())
{
    using (var s = client.GetStreamAsync("https://via.placeholder.com/150"))
    {
        using (var fs = new FileStream("localfile.jpg", FileMode.OpenOrCreate))
        {
            s.Result.CopyTo(fs);
        }
    }
}

Note that GetStreamAsync returns a task, so we use the Result property to get the stream. However, this can lead to deadlocks in certain scenarios.

A better approach is to use the asynchronous version:

using var client = new HttpClient();
using var s = await client.GetStreamAsync("https://via.placeholder.com/150");
using var fs = new FileStream("localfile.jpg", FileMode.OpenOrCreate);
await s.CopyToAsync(fs);

This way, we avoid blocking the calling thread and ensure a more responsive application.

Best Practices

When downloading files from URLs, consider the following best practices:

  • Always check the status code of the HTTP response to ensure the download was successful.
  • Use asynchronous methods to avoid blocking the calling thread.
  • Handle exceptions and errors properly, such as network failures or invalid URLs.
  • Be mindful of file system permissions and security when saving downloaded files.

By following these guidelines and using the HttpClient class, you can write robust and efficient code for downloading files from URLs in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *