This post will discuss how to download a file from a URL in C#.

1. Using WebClient Class

The System.Net.WebClient class provides several utility methods for sending data and receiving data from a URI resource. You can use the WebClient.DownloadFile() method to download the resource with the specified URI to a local file. It takes two parameters – address, which is the URI from which to download data and the fileName, which is the name of the local file that is to receive the data. The following example downloads the jquery-3.6.1.min.js file from the https://code.jquery.com/ domain and saves the file to the local hard drive.

Download Code

 
Note that this method blocks the calling thread while downloading the resource. To download a resource asynchronously, consider using the DownloadFileAsync() method. You can also use the WebRequest class to make a request to a URI, as shown below:

Download Code

 
Note that both the WebClient and WebRequest class are obsolete and results in the following warning.

warning SYSLIB0014: ‘WebClient.WebClient()’ is obsolete: ‘WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.’

2. Using HttpClient Class

It is preferable to use the HttpClient class from the System.Net.Http namespace. You can use the HttpClient.GetStringAsync() method to asynchronously return the response as a string from the specified Uri, which then can be written to the file system.

Download Code

That’s all about downloading a file from a URL in C#.