Repository navigation
Description
Forward-Only ZIP Archive Reading API Proposal
Motivation: Enable streaming ZIP reads without whole-archive buffering or third-party dependencies.
Proposed API
Add ZipArchiveMode.ForwardRead for sequential ZIP reading without whole-archive buffering. Reuse ZipArchiveEntry, its owning archive, and existing opening/extraction APIs.
namespace System.IO.Compression;
public enum ZipArchiveMode
{
Read = 0,
Create = 1,
Update = 2,
+ ForwardRead = 3
}
public partial class ZipArchive
{
+ public ZipArchiveEntry? GetNextEntry();
+ public ValueTask<ZipArchiveEntry?> GetNextEntryAsync(CancellationToken cancellationToken = default);
}
public partial class ZipArchiveEntry
{
+ public bool TryGetLength(out long length);
+ public bool TryGetCompressedLength(out long compressedLength);
+ [CLSCompliant(false)]
+ public bool TryGetCrc32(out uint crc32);
}Use existing constructors and read-only Open/OpenAsync overloads, including those accepting ReadOnlySpan<char> passwords. GetNextEntry and GetNextEntryAsync require ForwardRead; they throw NotSupportedException in Read, Create, and Update modes.
Usage
using ZipArchive archive = new(httpResponseStream, ZipArchiveMode.ForwardRead);
while (archive.GetNextEntry() is { } entry)
{
using Stream data = entry.Open();
ProcessEntry(entry.FullName, data);
}Available and unavailable members
| Member | ForwardRead behavior |
|---|---|
ZipArchive.Mode |
Returns ForwardRead |
All CreateEntry overloads |
Throw NotSupportedException, as in ordinary Read mode |
ZipArchive.Entries, GetEntry |
Throw NotSupportedException: indexed access is unavailable, unlike ordinary Read mode |
Archive Comment getter/setter |
Throw NotSupportedException: the comment is in the unparsed end record. Ordinary Read exposes it and permits in-memory changes without saving them |
Entry Archive, FullName, Name, LastWriteTime getter, CompressionMethod, IsEncrypted, EncryptionMethod |
Readable immediately after GetNextEntry, before opening or reading the payload. |
Existing entry Length, CompressedLength, Crc32 properties |
Expose known values; throw InvalidOperationException while unknown |
Entry Comment, ExternalAttributes getters/setters, VersionMadeBy getter |
Always throw NotSupportedException |
Setting LastWriteTime, deleting entries, opening for writing |
Unsupported |
ExtractToFile / ExtractToFileAsync |
Supported with adaptations: omit unavailable size preallocation and central-directory permission restoration |
ExtractToDirectory / ExtractToDirectoryAsync |
Supported through sequential advancement, not archive.Entries |
Behavior and limitations
Reading input and entry contents
Reuse existing ZipArchiveEntry.Open/OpenAsync methods, including password overloads. Traversal cannot continue after a faulty or unsupported entry.
- Metadata comes from local headers and completed data descriptors, not the central directory.
TryGetLength(uncompressed size),TryGetCompressedLength, andTryGetCrc32do not consume input: they returnfalsewith a zero output while unknown, ortruewith the available value; availability does not imply integrity validation.
Compression, encryption, and data descriptors
"Known size" means the compressed size is in the local header or its ZIP64 extra field, without a data descriptor. A descriptor is a record after the entry data containing its sizes and CRC.
| Compression | Encryption | Known size, no descriptor | Descriptor present |
|---|---|---|---|
| Stored | None | Supported | Unsupported |
| Deflate / Deflate64 | None | Supported | Supported |
| Stored | ZipCrypto / WinZip AES | Supported | Unsupported |
| Deflate / Deflate64 | ZipCrypto / WinZip AES | Supported | Unsupported |
| Other methods | Any | Unsupported | Unsupported |
Advancement and usage
GetNextEntrydrains unread data: unopened known-size entries are skipped without integrity checks; opened entries and supported descriptor entries are completed and validated.- Open each entry once and finish processing before advancing; previous payloads cannot be reopened and overlapping operations are rejected. Check
TryGetresults, enforce resource limits and safe extraction paths, and let the archive exclusively read the source.
Alternative design: ZipStreamReader
A dedicated reader and entry provide a narrower API, but add public types instead of reusing ZipArchiveEntry and its owning archive. Returning ZipArchiveEntry from this reader would still require a meaningful Archive owner, such as a backing forward-reading archive. The format limitations above apply to either design.
namespace System.IO.Compression;
public sealed class ZipStreamReader : IDisposable, IAsyncDisposable
{
public ZipStreamReader(Stream stream, bool leaveOpen = false);
public ZipStreamReader(
Stream stream, Encoding? entryNameEncoding, bool leaveOpen = false);
public ZipStreamEntry? GetNextEntry();
public ValueTask<ZipStreamEntry?> GetNextEntryAsync(
CancellationToken cancellationToken = default);
public void Dispose();
public ValueTask DisposeAsync();
}
public sealed class ZipStreamEntry
{
internal ZipStreamEntry();
public string FullName { get; }
public string Name { get; }
public DateTimeOffset LastWriteTime { get; }
public ZipCompressionMethod CompressionMethod { get; }
public ZipEncryptionMethod EncryptionMethod { get; }
public bool IsEncrypted { get; }
public bool TryGetLength(out long length);
public bool TryGetCompressedLength(out long compressedLength);
[CLSCompliant(false)]
public bool TryGetCrc32(out uint crc32);
public Stream Open();
public Stream Open(ReadOnlySpan<char> password);
public Task<Stream> OpenAsync(CancellationToken cancellationToken = default);
public Task<Stream> OpenAsync(
ReadOnlySpan<char> password, CancellationToken cancellationToken = default);
}
// In System.IO.Compression.ZipFile, sharing the extraction implementation.
public static class ZipStreamEntryExtensions
{
public static void ExtractToFile(
this ZipStreamEntry source, string destinationFileName, bool overwrite = false);
public static void ExtractToFile(
this ZipStreamEntry source, string destinationFileName, ZipExtractionOptions options);
public static Task ExtractToFileAsync(
this ZipStreamEntry source, string destinationFileName, bool overwrite = false,
CancellationToken cancellationToken = default);
public static Task ExtractToFileAsync(
this ZipStreamEntry source, string destinationFileName, ZipExtractionOptions options,
CancellationToken cancellationToken = default);
}Details
Initial content:
This was started in https://github.com/dotnet/corefx/issues/9657
There seems to be a growing desire/need for a forward-only API that accesses compressed file formats (e.g. zip, gzip, tar, etc.) in a streaming manner. This means very large files as well as streams like network streams can be read and decompressed on the fly. Basically, the API reads from Stream objects and never seeks on it. This is how the Reader/Writer API from SharpCompress works.
Here's a sample from the unit tests:
using (Stream stream = new ForwardOnlyStream(File.OpenRead(path)))
using (IReader reader = ReaderFactory.Open(stream))
{
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
reader.WriteEntryToDirectory(test.SCRATCH_FILES_PATH, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
}
}
public interface IReader : IDisposable
{
event EventHandler<ReaderExtractionEventArgs<IEntry>> EntryExtractionProgress;
event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
ArchiveType ArchiveType { get; }
IEntry Entry { get; }
/// <summary>
/// Decompresses the current entry to the stream. This cannot be called twice for the current entry.
/// </summary>
/// <param name="writableStream"></param>
void WriteEntryTo(Stream writableStream);
bool Cancelled { get; }
void Cancel();
/// <summary>
/// Moves to the next entry by reading more data from the underlying stream. This skips if data has not been read.
/// </summary>
/// <returns></returns>
bool MoveToNextEntry();
/// <summary>
/// Opens the current entry as a stream that will decompress as it is read.
/// Read the entire stream or use SkipEntry on EntryStream.
/// </summary>
EntryStream OpenEntryStream();
}WriteEntryToDirectory is an extension method that provides some shortcuts for dealing with file operations but what it really does is just grab the internal stream and decompresses. The actual entry method is just IReader.WriteEntryTo(Stream); If the entry isn't decompressed then the internal stream is just moved forward and not decompressed if possible (some formats require decompression since compressed length can be unknown)
The Writer API works similarly.
There is also a generic API from ReaderFactory or WriterFactory that doesn't require knowledge of the format beforehand. There is also a similar ArchiveFactory that is writeable (that uses WriterFactory internally to save) that could also be used for the current ZipArchive API and beyond.
As the author of SharpCompress, I'd like to push a lot of the ideas into core library but having native access to the compression streams (like the internal zlib) would be a great performance benefit for me. I haven't ever written any compression algorithm implementations myself so I'm sure my managed implementations need a lot of love.
I would start by creating ZipReader and ZipWriter (as well as starting the generic API) using a lot of the internal code already in the core library to prove out the API. This kind of relates to https://github.com/dotnet/corefx/issues/14853 but forward-only access is something most libraries don't account for so I'm not sure. Other easy additions would be Reader/Writer support for GZip, BZip2 and LZip (with an LZMA compressor).
Tar support linked with the previous single file formats would be a larger addition. SharpCompress deals with tar.gz, tar.bz2 and tar.lz auto-magically by detecting first the compressed format then a tar file inside. The above API works the same.
Thoughts?
Summoning a few people from the other issue
cc: @ianhays @karelz @qmfrederik
Activity
karelz commentedon Jun 12, 2017
@ianhays what is the next step? You did +1 above, does it mean you like the idea? Do we need API proposal? Or is it ready for API review? (Disclaimer: I just skimmed through it)
adamhathcock commentedon Jun 12, 2017
I can put together a new API based on what I've done. It would be very similar to SharpCompress.
svick commentedon Jun 12, 2017
ZipArchivealready supports writing to non-seekable streams on .Net Core (https://github.com/dotnet/corefx/issues/11497).IEnumerable<T>. That way, the user can use aforeachand they don't have to manually call something likeMoveNextin awhileloop. (Some LINQ methods also become a possibility.)adamhathcock commentedon Jun 12, 2017
ReaderAPI and it would have a generic writing implementation while the current one is specific to Zip and could probably not apply in a generic case. If a generic API isn't desired then this could possibly be dropped.ToList()on the reader which would definitely not work and defeat the point of the reader API when they should have used the archive API.svick commentedon Jun 12, 2017
Then maybe the API should return a type that can be used in a
foreach, but does not implementIEnumerable<T>. Though that could be confusing to someone who sees the API for the first time.ianhays commentedon Jun 12, 2017
I've gone back-and-forth about this myself. I opened https://github.com/dotnet/corefx/issues/9709 to track my thoughts long-term on a way to centralize our compression algorithms somehow. It's clear that as we continue adding more compression types to corefx it's going to become trickier and tricker to integrate them smoothly and expose them to devs of all skill levels without being overwhelming or overly simplistic.
I think in this case increased usability is more valuable than protecting devs from themselves. You could implement a code analysis rule specifically to look for instances where devs do a
ToList()and suggest they avoid it.ianhays commentedon Jun 12, 2017
https://github.com/dotnet/corefx/issues/9237 is also somewhat related, though less so.
ianhays commentedon Jun 12, 2017
I do like the idea. My main concern is that I really want to do our compression expansion right. There are a ton of questions around design and usability that I want answered well before we take anything like this issue, dotnet/corefx#9237, or dotnet/corefx#9709. Adding something like LZMA is easy because we can model it after DeflateStream/GZipStream with a similar API, but this issue (and the others linked above) is far more complex in the long-term implications of its design and API expansion.
karelz commentedon Jun 12, 2017
OK, what is the next step? (you coming back with larger design?) What is rough ETA?
ianhays commentedon Jun 12, 2017
Continue discussing design choices in this issue, dotnet/corefx#9709, and dotnet/corefx#9237. Wait for other people to be interested and comment/vote on these threads with their opinion.
Whenever we reach quorum and have a sizable mass of users requesting the feature. It's not something that we're hurting for right now or that a lot of customers are asking for, so I don't feel comfortable assigning an ETA for it.
adamhathcock commentedon Jun 13, 2017
Here's a rough Reader API based on what I've done with SharpCompress and making the Reader itself be
IEnumerablemight not quite be correct.Sample usage
Can expand out to the show the generic Archive API too.
svick commentedon Jun 13, 2017
@ianhays
Would it then make sense to design (and implement) an initial version of the whole compression expansion in corefxlab? That way, all the related APIs can be designed together and easily inform each other.
adamhathcock commentedon Jun 13, 2017
Putting it wholesale together as a real thing in corefxlab makes sense. Evolving the API might be too slow.
ianhays commentedon Jun 13, 2017
That is probably the best idea. We can design the large structure in corefxlab, then move small pieces to corefx one-by-one with their own justification so that we can actually get them through API review.
I like that too. Your rough API is pretty similar to what I had in mind.
A couple suggestions:
ArchiveTypeexplicitly.PreservePermissionsentry.IReaderEntryandIEntry? Where is the latter used?IReader.WriteEntryToand friends, I think those should be extension methods on the IReaderEntry (or IEntry) itself.Reader/IReadershould be replaced withArchiveReaderorIArchiveReader(or something like that).On a more general note, could you explain why you split reading and writing to their own interfaces/classes? Having a single
IArchiveseems more intuitive and usable despite opening up some notsupported operations e.g. attempting to write to an archive that is being read.ianhays commentedon Jun 13, 2017
It should be possible to combine this with the concept of a compression algorithm interface a la https://github.com/dotnet/corefx/issues/9709.
23 remaining items
iUnknwn commentedon Jun 2, 2020
Wanted to add a bit more information on this topic - I am one of the authors' of Microsoft SimpleRemote that we use for testing in Surface, and we ended up using a 3rd party tar library because there was no way to do forward-only operations with what's included in the current Compression namespace.
This is less of an API defect and more of a problem with the zip format itself - Zip is easy to stream when writing to it, because it stores metadata for the files at the end of the archive, so you can easily write to the stream without ever seeking. Reading, however, is incredibly difficult, because you need to read end of the file before operating on the archive.
To address this, if you try to open a non-seekable stream with ZipArchive, .NET internally reads the entire stream into a memory stream before processing (this works in some cases, but does not work on zip files larger than 4GB, as memory stream does not support streams larger than int32 bytes).
Here's an example of where this is a problem: Let's say you're reading a zip stream over a network - this means you'd need to download the entire file before being able to access any of the contents. If we compare this to tar (or cpio, or any tar-like format), we don't have this restriction - we can freely read elements as they come in, since all metadata for a given file is just before that file.
This is a problem for any case where the source stream does not support seeking (if we're encrypting data using cryptostreams, for example, they also aren't seekable). Adding tar, or another archive that supports forward only reads and writes, would make these scenarios much more straightforward and performant.
One note, though - if we implement tar, please use something that, at minimum, supports USTAR (and, ideally, supports the 2001 PAX extensions, so we can write files with unlimited size - historic tar has an 8GB/entry cap).
adamhathcock commentedon Jun 4, 2020
SharpCompress does what you need but the Tar support isn’t super great. Would love help expanding it.
iUnknwn commentedon Jun 9, 2020
@adamhathcock I'll take a look! From a quick glance at the code, it looks like SharpCompress Tar entries are USTAR + GNU extensions, correct? It should be pretty easy to add basic support for PAX extensions for long-file, long-link, and large sizes.
bjh0 commentedon Sep 6, 2021
Is there an update on this issue? This issue affects my use of the OpenXML SDK.
Add ZipStreamReader for forward-only reading of ZIP archives