Recipe 10.6 · C#
Streaming Large Files
Problem
Code that worked with test files falls over with production ones. File.ReadAllBytes on a 3 GB extract throws OutOfMemoryException, or pushes a web server into constant garbage collection. File.ReadAllLines loads every line before the first is processed. And integrity checks compute a hash in a second pass, reading the whole file twice.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
byte[] data = File.ReadAllBytes(source);
string hash = BitConverter.ToString(MD5.Create().ComputeHash(data));
File.WriteAllBytes(destination, data);
The whole file is in memory, twice in places, and the hash uses MD5.
The improved recipe
Copy in fixed-size chunks with a pooled buffer, hash each chunk as it passes through, and report progress. For text, read lines lazily.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Files;
public static class FileStreaming
{
private const int ChunkSize = 128 * 1024;
public static async Task<string> CopyWithHashAsync(
string sourcePath,
string destinationPath,
IProgress<long>? progress = null,
CancellationToken ct = default)
{
var readOptions = new FileStreamOptions
{
Mode = FileMode.Open,
Access = FileAccess.Read,
Share = FileShare.Read,
Options = FileOptions.Asynchronous
| FileOptions.SequentialScan,
BufferSize = 0
};
await using var source =
new FileStream(sourcePath, readOptions);
var writeOptions = new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
Options = FileOptions.Asynchronous,
BufferSize = 0,
PreallocationSize = source.Length
};
await using var destination =
new FileStream(destinationPath, writeOptions);
using var hash =
IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
byte[] buffer = ArrayPool<byte>.Shared.Rent(ChunkSize);
try
{
long total = 0;
int read;
while ((read = await source.ReadAsync(
buffer.AsMemory(0, ChunkSize), ct)) > 0)
{
hash.AppendData(buffer, 0, read);
await destination.WriteAsync(
buffer.AsMemory(0, read), ct);
total += read;
progress?.Report(total);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
return Convert.ToHexString(hash.GetHashAndReset())
.ToLowerInvariant();
}
public static async Task<string> HashFileAsync(
string path, CancellationToken ct = default)
{
await using var stream = new FileStream(path, FileMode.Open,
FileAccess.Read, FileShare.Read, ChunkSize,
FileOptions.Asynchronous | FileOptions.SequentialScan);
byte[] digest = await SHA256.HashDataAsync(stream, ct);
return Convert.ToHexString(digest).ToLowerInvariant();
}
public static IEnumerable<string> ReadMatchingLines(
string path, Func<string, bool> predicate) =>
File.ReadLines(path).Where(predicate);
}
How it works
CopyWithHashAsync holds one 128 KB buffer, rented from the shared ArrayPool so repeated copies do not allocate. Each chunk is read once, added to the hash and written out, so the file is read a single time whatever its size. IncrementalHash is the streaming form of SHA-256; the result is the same lowercase hex string that sha256sum or PowerShell's Get-FileHash produce (PowerShell prints it in uppercase), which makes it easy to compare with a partner's checksum file.
BufferSize = 0 turns off FileStream's internal buffer, since the code already reads and writes in large chunks and a second buffer would only copy memory. SequentialScan tells Windows to read ahead aggressively. PreallocationSize asks the file system to reserve the full size up front, which reduces fragmentation and fails early if the disk is too small.
HashFileAsync is the one-liner for a checksum alone; SHA256.HashDataAsync(Stream) (.NET 7 and later) streams internally.
File.ReadLines in ReadMatchingLines returns lines lazily, so filtering a 5 GB log uses a few kilobytes of memory.
Variations and pitfalls
- Web downloads. In ASP.NET Core, return
Results.File(path, contentType, enableRangeProcessing: true). The server streams from disk and supports resumable downloads. Never read the file into a byte array first. - Web uploads.
IFormFilebuffers uploads larger than 64 KB to a temp file, which is fine for most sizes. For multi-gigabyte uploads, readRequest.BodywithMultipartReaderand stream straight to storage.