How to process ZIP Files from a Stream in .NET

How to process ZIP Files from a Stream in .NET

When working with ZIP files in .NET, there may be cases where the file is not stored on disk but comes directly as a Stream. This could happen if you're downloading the ZIP file from a network, receiving it via an API, or working with in-memory file data. In this blog post, I’ll show you a simple example of handling ZIP files using streams in .NET and how to process their content without saving the ZIP to disk.

Why Use Streams for ZIP Files?

Using streams to handle ZIP files provides several advantages:

  • Memory Efficiency: Working with streams avoids the need to store files on disk, which is useful in cloud applications and microservices.
  • Direct Data Processing: Process files as soon as they're received, without the need to store or clean up temporary files.
  • Increased Security: Avoids file system access and reduces the need to manage temporary storage locations.
namespace BenjaminAbt.ZipFileSample;

using System.IO;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        // stream from API Controller, File.Open....
        Stream zipStream = ..

        using ZipArchive archive = new(zipStream, ZipArchiveMode.Read);

        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            // e.g. read file in-memory
            using StreamReader r = new(entry.Open());

            // use content as steam
            string content = r.ReadToEnd();

            // handle file here

        }
    }
}

Practical Use Cases for Stream-Based ZIP Handling

  • API Data Processing: If your application receives ZIP files via HTTP, this approach allows you to handle the data without saving it.
  • In-Memory Data Analysis: ZIP files containing logs, configurations, or other textual data can be processed directly in memory.
  • Cloud and Serverless Environments: This is ideal in cloud services where persistent storage might be limited or where operations need to be stateless.

Final Thoughts

With this code snippet, handling ZIP files directly from a stream in .NET becomes straightforward and efficient. By using the ZipArchive and StreamReader classes, you can read and process file content without needing to write to disk, making it a perfect solution for modern, cloud-friendly apps.