Download a file with .NET

Download a file with .NET

The most current and currently recommended way to download .NET Framework, .NET Standard or .NET Core files from the Internet is the HttpClient class.

To use the HttpClient class, the NuGet package System.Net.Http is required.

<PackageReference Include="System.Net.Http" Version="4.3.4" />

public class DownloadFileSample
{
	// define HttpClient as static and re-use instance
	private static readonly HttpClient _httpClient = new HttpClient();

	public async Task<YourReturnHere> DownloadFile(string url)
	{
		// executes a HTTP "GET" request
		HttpResponseMessage response = await _httpClient.GetAsync(url);

		// download contents as string
		string responseBody = await response.Content.ReadAsStringAsync();

		// download contents as byte array
		string responseBody = await response.Content.ReadAsByteArrayAsync();

		// use contents as stream
		string responseBody = await response.Content.ReadAsStreamAsync();
	}
}

As you can see, the HttpClient or the Response offers several ways to handle the content: String, Byte Array or directly as stream. Make sure to use the appropriate way at this point. This improves performance.