---
title: "Write a ZIP to a non-seekable stream in C#"
url: https://recursiveai.org/onearchive/cookbook/write-zip-to-non-seekable-stream/
description: "Write a ZIP to a non-seekable stream in C# without going back to patch headers. Add two entries, finish the ZIP, and read the captured bytes."
version: "1.2.0"
---

# Write a ZIP to a non-seekable stream in C#

**OneArchive** is a free, open-source archive and compression library for .NET from Recursive AI: zip, tar, 7z, RAR and more in RecursiveAI.OneArchive, with compression codecs in RecursiveAI.OneCompress. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneArchive) · [GitHub](https://github.com/recursive-ai-oss/onearchive-csharp) · [Docs](https://recursiveai.org/onearchive/docs/) · [Download example (.zip)](https://recursiveai.org/onearchive/cookbook/write-zip-to-non-seekable-stream/write-zip-to-non-seekable-stream.zip)

Pass a forward-only stream, such as a pipe, to `ZipWriter`. Call `Finish` after the last entry.

```shell
dotnet add package RecursiveAI.OneArchive
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneArchive;
using RecursiveAI.OneArchive.Zip;
using var output =
    Console.OpenStandardOutput();
using var zip = new ZipWriter(output);
zip.WriteEntry(new() { Name = "a.txt",
    Size = 1 }, "A"u8.ToArray());
zip.WriteEntry(new() { Name = "b.txt",
    Size = 1 }, "B"u8.ToArray());
zip.Finish();
```

Unzip [the example](https://recursiveai.org/onearchive/cookbook/write-zip-to-non-seekable-stream/write-zip-to-non-seekable-stream.zip), then `dotnet run`.

The snippet at the top writes binary ZIP bytes, not text. In a shell such as Bash, run `dotnet build` once, then `dotnet run --no-build > pair.zip` to capture those bytes. `pair.zip` contains `a.txt` (`A`) and `b.txt` (`B`). Run the downloaded example normally instead; it captures the bytes in memory and prints the names.

## The full program

The program wraps a `MemoryStream` in a write-only stream whose `CanSeek` is `false` and whose seek operations throw. It writes the same two one-byte entries, finishes the ZIP, then rewinds only the underlying buffer and opens it for reading.

```csharp
using RecursiveAI.OneArchive;
using RecursiveAI.OneArchive.Zip;

using var capture = new MemoryStream();
using var output = new ForwardOnlyOutput(capture);
Console.WriteLine($"Can seek: {output.CanSeek}");

using (var zip = new ZipWriter(output, leaveOpen: true))
{
    zip.WriteEntry(new ArchiveEntry { Name = "a.txt", Size = 1 }, "A"u8.ToArray());
    zip.WriteEntry(new ArchiveEntry { Name = "b.txt", Size = 1 }, "B"u8.ToArray());
    zip.Finish();
}

capture.Position = 0;
using var archive = Archive.Open(capture);
foreach (var entry in archive.Entries)
    Console.WriteLine(entry.Name);

sealed class ForwardOnlyOutput(Stream sink) : Stream
{
    public override bool CanRead => false;
    public override bool CanSeek => false;
    public override bool CanWrite => true;
    public override long Length => throw new NotSupportedException();
    public override long Position
    {
        get => throw new NotSupportedException();
        set => throw new NotSupportedException();
    }

    public override void Flush() => sink.Flush();
    public override void Write(byte[] buffer, int offset, int count) =>
        sink.Write(buffer, offset, count);
    public override int Read(byte[] buffer, int offset, int count) =>
        throw new NotSupportedException();
    public override long Seek(long offset, SeekOrigin origin) =>
        throw new NotSupportedException();
    public override void SetLength(long value) => throw new NotSupportedException();
}
```

```text
Can seek: False
a.txt
b.txt
```

If you force `ZipDataDescriptorMode.Never` on a non-seekable stream, the `ZipWriter` constructor throws `ArgumentException`.

## Variations

**Use descriptors even when the output can seek.** This writes to a `MemoryStream` directly but still puts the CRC and sizes after the entry, just as in the forward-only example. 

```csharp
using RecursiveAI.OneArchive;
using RecursiveAI.OneArchive.Zip;
using var output = new MemoryStream();
using var zip = new ZipWriter(output,
    new ZipWriterOptions
    { DataDescriptors = ZipDataDescriptorMode.Always },
    leaveOpen: true);
zip.WriteEntry(new() { Name = "a.txt",
    Size = 1 }, "A"u8.ToArray());
zip.Finish();
output.Position = 0;
using var archive = Archive.Open(output);
Console.WriteLine(archive.Entries.Single().Name);
```

```text
a.txt
```

## Related recipes

- [Create a ZIP file](https://recursiveai.org/onearchive/cookbook/create-zip/)
- [Copy ZIP entries without recompressing](https://recursiveai.org/onearchive/cookbook/copy-zip-entries-without-recompressing/)

## The short answer

Give `ZipWriter` a writable stream, even if `CanSeek` is `false`. Write each entry and call `Finish` before closing the output. With the default `ZipDataDescriptorMode.Auto` mode, the writer puts each deflated file’s CRC-32 and sizes after its compressed bytes instead of seeking backward to update its header.

## How do I stream a ZIP file from C#?

Pass the real destination stream to the writer instead of creating a ZIP file on disk first. Each call to `WriteEntry` takes the archive name, the uncompressed length, and the content. For the sample’s two ASCII letters that length is one byte each. For an existing file use its byte length; don’t substitute a character count for the length of encoded text. An entry whose actual length differs from the declared size fails with `ArgumentException`.

Keep one writer open for the whole response and call `Finish` once after the last entry. It writes the central directory, the index normally read from the end of a ZIP, and the end records. Starting to send bytes does not mean the recipient already has a complete ZIP. If the caller owns the output stream, pass `leaveOpen: true` so disposing the writer doesn’t close it. The in-memory buffer in this recipe makes the result easy to reopen; it isn’t required for writing to a pipe.

In an ASP.NET Core endpoint, write to `Response.Body` with the async methods. Here, `context` is the endpoint’s `HttpContext`:

```csharp
using RecursiveAI.OneArchive;
using RecursiveAI.OneArchive.Zip;

context.Response.ContentType = "application/zip";
await using var zip = new ZipWriter(
    context.Response.Body, leaveOpen: true);
using var content = new MemoryStream("A"u8.ToArray());
await zip.WriteEntryAsync(
    new ArchiveEntry { Name = "a.txt", Size = 1 },
    content, context.RequestAborted);
await zip.FinishAsync(context.RequestAborted);
```

## What is a ZIP data descriptor?

A data descriptor is a record that follows an entry’s data. It carries the CRC-32, compressed size, and uncompressed size. The compressed size isn’t known at the start of a deflated entry. When the output can seek, `Auto` goes back and fills in the local header after compression. When the output can’t seek, `Auto` marks the header to signal a descriptor and writes the final values after the data instead. Neither case removes the central directory at the end.

Directories, links, and empty files don’t need descriptors in OneArchive. A nonempty stored entry with a descriptor still gives its sizes in the local header so a forward-only reader can find its end. The [ZIP writer notes](https://recursiveai.org/onearchive/docs/archive/#writing-byte-exact-1) describe those exceptions and the ZIP64 layout.
