© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•14mo ago•
68 replies
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?
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);
}
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);
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,828Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

Downloading a file onto a project
C#CC# / help
3y ago
✅ Downloading file with HttpClient does not work
C#CC# / help
14mo ago
Azure Appserice 502 when upload large file [Answered]
C#CC# / help
4y ago