The feature request sounds small. "Let users download all of their documents as one zip file." Or the reverse: "Let customers upload a zip of CSV files, and we will import them."
Most implementations I review handle both the same way: build everything in a MemoryStream, call ToArray(), and move on. It works in testing with five files. In production, with five hundred files or one unexpectedly large upload, memory climbs, requests slow down, and occasionally someone downloads a zip that Windows says is invalid. Zip handling in .NET isn't hard, but a few details matter a lot. Let's dive in!
Bug 1: The Zip That Is Corrupt Only Sometimes
Here is a pattern I have seen in more than one codebase. It looks reasonable:
public static byte[] BuildZip(IEnumerable<(string Name, byte[] Content)> files)
{
using var buffer = new MemoryStream();
using var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true);
foreach (var (name, content) in files)
{
var entry = archive.CreateEntry(name);
using var entryStream = entry.Open();
entryStream.Write(content);
}
// BUG: the archive has not been disposed yet
return buffer.ToArray();
}
A zip file ends with a central directory, the index that lists every entry. ZipArchive writes it when the archive is disposed. With using declarations, disposal happens at the end of the method, which is after ToArray() has already copied the bytes. The result is missing its index. Some tools can recover the entries by scanning, so the bug can survive testing; others reject the file outright.
The fix is to make the archive's lifetime explicit, and finish it before reading the buffer:
public static byte[] BuildZip(IEnumerable<(string Name, byte[] Content)> files)
{
using var buffer = new MemoryStream();
using (var archive = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (var (name, content) in files)
{
var entry = archive.CreateEntry(name);
using var entryStream = entry.Open();
entryStream.Write(content);
}
} // central directory is written here
return buffer.ToArray();
}
Note leaveOpen: true. Without it, disposing the archive also closes the MemoryStream. (ToArray() happens to still work on a closed MemoryStream, but if you set Position = 0 and hand the stream to something else, it will not.) This version is correct. It is also still holding the entire archive in memory, and then copying it a second time with ToArray(). That is the next problem.
Bug 2: Buffering the Whole Download
For a download endpoint, the buffer is not needed at all. A zip created in ZipArchiveMode.Create can be written front to back to a stream that does not support seeking, and an HTTP response body is exactly that kind of stream. You can compress each file as you read it and send the bytes as they are produced.
Historically, there was a catch. Kestrel and IIS disallow synchronous I/O on the response by default, and ZipArchive only had synchronous APIs, so streaming a zip directly to the response tended to end with an exception when the archive was disposed. Teams went back to the MemoryStream.
.NET 10 removed that excuse. It added async ZIP APIs, including ZipArchive.CreateAsync, ZipArchiveEntry.OpenAsync, and asynchronous disposal on ZipArchive. Here is a minimal API endpoint that streams a zip of stored files straight to the browser:
using System.IO.Compression;
app.MapGet("/batches/{batchId:guid}/download",
async (Guid batchId, HttpContext http, IDocumentStore store, CancellationToken ct) =>
{
IReadOnlyList<StoredDocument> documents = await store.ListAsync(batchId, ct);
if (documents.Count == 0)
{
return Results.NotFound();
}
http.Response.ContentType = "application/zip";
http.Response.Headers.ContentDisposition =
$"attachment; filename=\"batch-{batchId:N}.zip\"";
await using (var archive = await ZipArchive.CreateAsync(
http.Response.Body, ZipArchiveMode.Create, leaveOpen: true,
entryNameEncoding: null, cancellationToken: ct))
{
foreach (var document in documents)
{
// PDFs and images are already compressed; Fastest saves CPU
var entry = archive.CreateEntry(document.FileName, CompressionLevel.Fastest);
await using var target = await entry.OpenAsync(ct);
await using var source = await store.OpenReadAsync(document, ct);
await source.CopyToAsync(target, ct);
}
} // central directory is written here, asynchronously
return Results.Empty;
});
IDocumentStore and StoredDocument stand in for wherever your files live: Blob Storage, a file share, or a database. The important part is that each file is read, compressed, and written to the response one at a time. Memory use depends on the copy buffer and the compressor, not on the size of the download.
Three trade-offs to know before you ship it:
- Once the first byte is sent, the status code is committed. Do your authorization, lookups, and "does this batch exist" checks before writing anything, as the example does. If reading a file fails halfway through, the client gets a truncated download, not a clean error.
- There is no Content-Length. Browsers will show progress without a total size. For most business downloads, that is fine.
- Entry names come from your data. If file names are user-supplied, normalize them and handle duplicates, because two entries with the same name make a confusing archive.
If you need the zip as bytes for some other reason, such as attaching it to an email, the corrected BuildZip from Bug 1 is fine for small, bounded sets of files. Just make it a deliberate choice, with a limit, rather than the default.
Reading an Uploaded Zip Without Trusting It
The upload direction has a different risk. A zip from a user is untrusted input, and a small compressed file can expand to an enormous amount of data. Microsoft's best practices for ZIP and TAR archives is direct about it: neither ZipArchive nor the ExtractToDirectory helpers limit total uncompressed size or entry count. You have to enforce those limits yourself.
The good news is that a zip's central directory tells you each entry's declared uncompressed size before you decompress anything, and the runtime will not produce more than entry.Length bytes when you open an entry. So you can check everything up front and reject the archive cheaply. Here is an import endpoint that processes CSV files straight from the upload, without ever extracting to disk:
using System.IO.Compression;
const int MaxEntries = 200;
const long MaxEntryBytes = 25L * 1024 * 1024; // 25 MB per file
const long MaxTotalBytes = 250L * 1024 * 1024; // 250 MB for the whole archive
app.MapPost("/imports",
async (IFormFile upload, ICsvImporter importer, CancellationToken ct) =>
{
await using var uploadStream = upload.OpenReadStream();
await using var archive = await ZipArchive.CreateAsync(
uploadStream, ZipArchiveMode.Read, leaveOpen: false,
entryNameEncoding: null, cancellationToken: ct);
if (archive.Entries.Count > MaxEntries)
{
return Results.BadRequest($"The archive contains more than {MaxEntries} entries.");
}
// Validate everything before importing anything
var csvEntries = new List<ZipArchiveEntry>();
long totalBytes = 0;
foreach (var entry in archive.Entries)
{
if (string.IsNullOrEmpty(entry.Name))
{
continue; // directory entry
}
if (!entry.Name.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
{
continue; // ignore files we do not import
}
if (entry.Length > MaxEntryBytes)
{
return Results.BadRequest($"'{entry.Name}' is larger than the per-file limit.");
}
totalBytes = checked(totalBytes + entry.Length);
if (totalBytes > MaxTotalBytes)
{
return Results.BadRequest("The archive is larger than the total size limit.");
}
csvEntries.Add(entry);
}
foreach (var entry in csvEntries)
{
await using var content = await entry.OpenAsync(ct);
await importer.ImportAsync(entry.Name, content, ct);
}
return Results.Ok(new { Imported = csvEntries.Count });
});
A few details worth calling out:
- Validate first, import second. Checking every entry before importing any of them means a bad archive is rejected as a whole, instead of half-imported.
- The entry is never written to disk. The importer reads the decompressed stream directly. If you do need to extract to disk, use a fresh directory your app controls and validate each destination path with
Path.GetFullPath, as the best-practices article shows. Do not hand an uploaded archive toExtractToDirectory; Microsoft's guidance is to use it only for trusted input. - Seekable input matters.
IFormFilegives you a seekable stream. If you open a zip inReadmode over a stream that cannot seek, such as a raw network stream, the runtime buffers the entire archive in memory to reach the central directory at the end. Read uploads throughIFormFileor save them to a temporary file first. - Request limits still apply. These checks protect you from what is inside the archive. Keep sensible request body and multipart size limits for the upload itself.
If your app uses the antiforgery middleware (Blazor Web Apps do), form-based minimal API endpoints like this one validate an antiforgery token by default. That is what you want for a browser form. For an API called with a bearer token, make the choice explicitly rather than discovering it in production.
On .NET 11, there is a bonus: the runtime now validates each entry's CRC-32 when you read it to the end, and throws InvalidDataException on a mismatch. Earlier versions accepted corrupt entries silently. That is accidental-corruption protection, not tamper protection, but it is one more reason to be on a current runtime.
One More: Avoid Update Mode for Anything Large
ZipArchiveMode.Update is convenient for "add one file to this zip." Behind the scenes, opening an entry's content in Update mode loads its uncompressed data into a MemoryStream. For a small archive you trust, that is fine. For a large one, or one that came from a user, it is an OutOfMemoryException waiting to happen. Microsoft's recommended alternative is to open the original in Read mode, create a new archive in Create mode, and copy across only the entries you want. Both modes stream entry data instead of buffering it.
The Conversation for Leaders
"Export to zip" and "import from zip" rarely get a design review because they sound like plumbing. They are also two of the few places where a single request can ask your server to hold an unbounded amount of data. If your applications have either feature, ask two questions: does the download buffer the whole archive in memory, and does the import enforce size and entry limits before decompressing anything? Both have straightforward fixes, and both are much cheaper to fix before the first big customer finds them.
Your Next Step
Search your solution for new MemoryStream() near ZipArchive, and for ExtractToDirectory. The first finds downloads you can convert to streaming. The second finds the places most likely to be trusting an archive they should not.
Categories