Start Debugging

C# ZIP files to Stream

.NET 8 includes new CreateFromDirectory and ExtractToDirectory overloads that let you create and extract ZIP files directly to and from a Stream, without writing to disk.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

.NET 8 includes new CreateFromDirectory overloads which enable you to create a ZIP file without writing it to disk. This is particularly useful in situations where you don’t need to store the zipped resources and only use the ZIP content for transfer.

If you are moving this workflow to .NET 10 or .NET 11, see creating and extracting ZIP files asynchronously for the newer APIs and their stream disposal differences.

For example: if you were to provide an API allowing multi-file download. That endpoint will most likely compress the selected files into a .zip and provide that for download. By using the new overloads, you can easily bypass the disk – reducing the load on the disk and offering a faster response time to your users.

public static void CreateFromDirectory(string sourceDirectoryName, Stream destination);

In addition to the overload above there are a couple more allowing you to configure some options such as compressionLevel, includeBaseDirectory and entryNameEncoding.

public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, CompressionLevel compressionLevel, bool includeBaseDirectory);
public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding);

Extract ZIP file from Stream

Similar to the CreateFromDirectory overloads, .NET 8 also includes new ExtractToDirectory overloads which enable you to extract a ZIP file directly from a Stream, without writing the intermediary .zip to disk. This is particularly useful in situations where you don’t want to store the Zip file and all you care about are the unzipped resources.

public static void ExtractToDirectory(Stream source, string destinationDirectoryName)

In addition to the overload above there are a few more allowing you to configure some options such as overwriteFiles and entryNameEncoding.

public static void ExtractToDirectory(Stream source, string destinationDirectoryName) { }
public static void ExtractToDirectory(Stream source, string destinationDirectoryName, bool overwriteFiles) { }
public static void ExtractToDirectory(Stream source, string destinationDirectoryName, Encoding? entryNameEncoding) { }
public static void ExtractToDirectory(Stream source, string destinationDirectoryName, Encoding? entryNameEncoding, bool overwriteFiles) { }

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.