C#C
C#13mo ago
Kiriox

Downloading large file

Hello, I need to be able to download files up to 400Mb asynchronously and track the download in a progress bar. I have this code except that it doesn't work totally, on 50Mb files it's fine but 130Mb it crashes and moreover it takes a while before starting the download. So I wanted to know if this was the right method and if it was possible to optimize it?
c#
int DefaultCopyBufferSize = 81920;
string destinationPath = Path.GetTempFileName();
using var client = new HttpClient();

using var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
using var source = await response.Content.ReadAsStreamAsync();
using var destination = File.OpenWrite(destinationPath);

int bytesRead;
var buffer = ArrayPool<byte>.Shared.Rent(DefaultCopyBufferSize);
var memory = buffer.AsMemory();

while ((bytesRead = await source.ReadAsync(memory)) > 0)
{
    await destination.WriteAsync(memory[..bytesRead]);
    progress.Increment(bytesRead);
}
Was this page helpful?