Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am I supposed to use ZipArchive with memory streams? [duplicate]

My problem is that as soon as ZipArchive is disposed, it automatically closes and disposes the MemoryStream. If I look at the stream before the disposal of ZipArchive the information is not well formed zip.

using (var compressStream = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(compressStream, ZipArchiveMode.Create))
    {
        // Adding a couple of entries
        string navStackInfo = Navigation.NavState.CurrentStackInfoLines();
        var navStackEntry = zipArchive.CreateEntry("NavStack.txt", CompressionLevel.NoCompression);
        using (StreamWriter writer = new StreamWriter(navStackEntry.Open()))
        {
             writer.Write(navStackInfo);
        }
        var debugInfoEntry = zipArchive.CreateEntry("CallStack.txt", CompressionLevel.Optimal);
        using (StreamWriter writer = new StreamWriter(debugInfoEntry.Open()))
        {
            // debugInfo.Details is a string too
            writer.Write(debugInfo.Details);
        }
        // ...
        // compressStream here is not well formed
    }
    // compressStream here is closed and disposed
}

So how should this work? Maybe the only problem is that it's not well formed? I see "PK" header number within the file (not just at the beginning) at the beginning of each entry part. I'm not sure if that's good or not. Certainly if I save the stream to a file I cannot open it as a zip file, something is wrong. (In the final code I do not want to materialize a file in a crash handling code though.)

like image 627
Csaba Toth Avatar asked Feb 12 '14 19:02

Csaba Toth


People also ask

How does ZipArchive work?

Extension MethodsArchives a file by compressing it and adding it to the zip archive. Archives a file by compressing it using the specified compression level and adding it to the zip archive. Extracts all the files in the zip archive to a directory on the file system.

What is a ZipArchive c#?

ZipArchive is a built-in package in the System. IO. Compression assembly to compress/decompress files in a zip format in C# code. It allows us to work with a collection of compressed files.


1 Answers

I just ran into the same issue, and I noticed that there's an optional parameter for the ZipArchive constructor called leaveOpen. Documentation says: True to leave the stream open after the System.IO.Compression.ZipArchive object is disposed; otherwise, false.

This solved the problem for me.

like image 96
Jeremy Avatar answered Oct 05 '22 00:10

Jeremy