To download a file in current .NET, use HttpClient: request the URL, then copy the response stream into a file. Streaming matters, because it keeps memory use flat no matter how big the file is.
Async download
using var http = new HttpClient();
await DownloadFileAsync(http, "https://www.example.com/files/test.jpg", "test.jpg");
static async Task DownloadFileAsync(
HttpClient http, string url, string path, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await http.GetAsync(
url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
await using Stream source = await response.Content.ReadAsStreamAsync(cancellationToken);
await using FileStream target = File.Create(path);
await source.CopyToAsync(target, cancellationToken);
}
Two details make the difference between this and a naive version:
HttpCompletionOption.ResponseHeadersReadreturns as soon as the headers have arrived. Without it,GetAsyncreads the entire body into memory first, which is the opposite of what you want for a 2 GB file.EnsureSuccessStatusCodethrows anHttpRequestExceptionfor 404, 500 and other error responses. Skip it and you save the server’s error page astest.jpg.
For small files, await http.GetByteArrayAsync(url) followed by File.WriteAllBytesAsync is shorter. It buffers the whole file in memory and is subject to HttpClient.Timeout (100 seconds by default) for the entire transfer, so keep it for files you know are small.
Reuse one HttpClient
HttpClient is meant to be created once and reused. Creating a new one per download, especially inside a loop, opens a new connection each time and can exhaust the available sockets under load. In a console tool, one instance for the lifetime of the program is fine. In ASP.NET Core, inject it through IHttpClientFactory (builder.Services.AddHttpClient()), which also handles DNS changes.
Report progress
CopyToAsync does not report progress, so for a progress bar copy in a loop and compare against Content-Length:
static async Task DownloadFileAsync(
HttpClient http, string url, string path,
IProgress<double>? progress = null, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await http.GetAsync(
url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
long? totalBytes = response.Content.Headers.ContentLength;
string tempPath = path + ".part";
await using (Stream source = await response.Content.ReadAsStreamAsync(cancellationToken))
await using (FileStream target = File.Create(tempPath))
{
byte[] buffer = new byte[81920];
long received = 0;
int read;
while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0)
{
await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
received += read;
if (totalBytes is > 0)
progress?.Report((double)received / totalBytes.Value);
}
}
// Only replace the real file once the download is complete.
File.Move(tempPath, path, overwrite: true);
}
Call it with a Progress<double> and a timeout:
using var http = new HttpClient();
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
var progress = new Progress<double>(p => Console.Write($"\r{p:P0}"));
await DownloadFileAsync(
http, "https://www.example.com/files/big.zip", "big.zip", progress, cts.Token);
Writing to a .part file and moving it at the end means a crash or cancellation never leaves a truncated big.zip that looks like a finished download. Delete the .part file in a catch block if you do not plan to resume.
Not every server sends Content-Length (chunked responses and some dynamic content do not), which is why totalBytes is nullable; without it you can only show the number of bytes received. Also note that Progress<T> posts its callback to the thread pool in a console app, so two reports can occasionally arrive out of order. In a WinForms or WPF app it runs on the UI thread, which is what you want for updating a progress bar.
Synchronous download
If you really need a blocking call, for example in an old code path that cannot become async, HttpClient.Send has existed since .NET 5:
using var http = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, "https://www.example.com/files/test.jpg");
using HttpResponseMessage response = http.Send(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using Stream source = response.Content.ReadAsStream();
using FileStream target = File.Create("test.jpg");
source.CopyTo(target);
Avoid http.GetAsync(url).Result as a shortcut. Blocking on a task can deadlock in UI apps and classic ASP.NET, and it wastes a thread everywhere else.
WebClient in older code
The original version of this post used WebClient.DownloadFile and DownloadFileAsync with its DownloadProgressChanged event. WebClient, WebRequest and HttpWebRequest are obsolete since .NET 6 (warning SYSLIB0014). They still work, but they get no new features, and on .NET Core and later HttpWebRequest, which WebClient uses, is itself implemented on top of HttpClient. Its event-based async methods also do not combine well with async/await. When you touch that code, replace it with the methods above.
code is not working. i want to download an image from different websites
I try it and it works. Can you send code sample for your usage?
Great Example, Thanks!
thanks for the great example!
nyc
can you write code how to download doc or pdf file and open that file in local computer c#