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.

1<PackageReference Include="System.Net.Http" Version="4.3.4" />
 1
 2public class DownloadFileSample
 3{
 4	// define HttpClient as static and re-use instance
 5	private static readonly HttpClient _httpClient = new HttpClient();
 6
 7	public async Task<YourReturnHere> DownloadFile(string url)
 8	{
 9		// executes a HTTP "GET" request
10		HttpResponseMessage response = await _httpClient.GetAsync(url);
11
12		// download contents as string
13		string responseBody = await response.Content.ReadAsStringAsync();
14
15		// download contents as byte array
16		string responseBody = await response.Content.ReadAsByteArrayAsync();
17
18		// use contents as stream
19		string responseBody = await response.Content.ReadAsStreamAsync();
20	}
21}

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.


Comments

Twitter Facebook LinkedIn WhatsApp