
Editorial illustration.
Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.
A bulk download button looks simple on paper: a user ticks five invoices or ten project attachments, clicks Download ZIP, and expects one archive to land in their Downloads folder. The UI part takes ten minutes. The real work is making sure the user is actually allowed to read every file in that bundle, keeping the archive valid when streams close, and deciding what happens when a file is missing or oversized.
Resolve files through application records
Never accept raw filesystem paths from a query string or form post. Start from authorised document IDs, verify the current user’s permission for every record in the selection, and map those IDs to trusted server paths or storage keys on the backend.
Archive entry names need the same care. If a user uploaded a file named ../../web.config or two separate records both happen to be called receipt.pdf, dumping raw names into CreateEntry will either confuse the extractor or overwrite entries silently. Strip directory segments with Path.GetFileName, sanitise invalid characters, and prefix or deduplicate colliding names using the record ID.
For a small, bounded set of already authorised files, the core System.IO.Compression pattern in C# looks like this:
public ActionResult DownloadBundle(int[] documentIds)
{
var authorisedFiles = _documentService.GetAuthorisedFiles(User, documentIds);
if (authorisedFiles.Count == 0)
{
return HttpNotFound();
}
using var output = new MemoryStream();
var usedNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using (var archive = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (var file in authorisedFiles)
{
if (!System.IO.File.Exists(file.ServerPath))
{
return new HttpStatusCodeResult(500, "Requested file is unavailable.");
}
var safeName = Path.GetFileName(file.DownloadName);
if (!usedNames.Add(safeName))
{
safeName = $"{file.Id}-{safeName}";
usedNames.Add(safeName);
}
var entry = archive.CreateEntry(safeName, CompressionLevel.Fastest);
using var destination = entry.Open();
using var source = System.IO.File.OpenRead(file.ServerPath);
source.CopyTo(destination);
}
}
return File(output.ToArray(), "application/zip", "documents-bundle.zip");
}
Two small details in that snippet save hours of debugging. First, CompressionLevel.Fastest (or NoCompression when bundling already-compressed PDFs, JPEGs, and DOCX files) avoids burning CPU for a 1% size difference. Second, usedNames guarantees every entry inside the ZIP has a distinct name.
Finish the archive before sending it
A classic bug with ZipArchive is reading output.ToArray() while the ZipArchive instance is still open. ZipArchive writes the ZIP central directory header only when it is disposed. If you copy or return the stream before archive.Dispose() runs, Windows Explorer and macOS Archive Utility will report the file as corrupted or empty.
Using leaveOpen: true on ZipArchive keeps the MemoryStream alive after the using (var archive = ...) block exits, so output.ToArray() captures the complete, finalised archive.
Watch the memory ceiling
Buffering an entire ZIP in a MemoryStream works cleanly for a handful of invoices totalling 10 MB or 20 MB. It breaks down quickly if users select 200 MB of CAD drawings or site photos at once: output.ToArray() allocates a second contiguous byte array on the Large Object Heap, and two or three concurrent downloads can push an IIS worker process into an out-of-memory restart.
Set an explicit upper limit on total uncompressed bytes or file count for synchronous downloads. Beyond that threshold, either stream directly to the HTTP response body (noting that ZipArchive in Create mode writes forward-only and works over non-seekable streams in modern .NET, though error recovery mid-stream is harder) or move the export to a background job that writes to disk or object storage and notifies the user when it is ready.
Decide how partial failure looks
If one of the selected files was deleted from disk or failed a storage read, do not quietly skip it and serve a smaller ZIP as if everything succeeded. Users notice missing invoices only during audits, long after the download happened. Either fail the request with a clear message, or include a documented manifest text file inside the archive listing which records were omitted and why.
Before shipping, test four cases manually: an empty selection, a single file, duplicate filenames across two records, and a missing file on disk. Open the downloaded ZIP in both the OS built-in extractor and a strict reader like unzip -t to confirm the central directory and entry headers are clean.