user1621791 user1621791 - 2 months ago 36
C# Question

Unzip a memorystream (Contains the zip file) and get the files

I have a memory stream that contains a zip file in byte[] format .

Is there any way I can unzip this memory stream, without any need of writing the file to disk ?

In general I am using ICSharpCode.SharpZipLib.Zip.FastZip to unzip a file ,
But any way to unzip a memory stream ? and store the files in another memorystream or in byte[] format according to the files/folders present in the zip ?

Any way I can use the Memorymapped files feature in this scenario ?

Answer

We use DotNetZip, and I can unzip the contents of a zip file from a Stream into memory. Here's the sample code for extracting a specifically named file from a stream (LocalCatalogZip) and returning a stream to read that file, but it'd be easy to expand on it.

    private static MemoryStream UnZipCatalog()
    {
        MemoryStream data = new MemoryStream();
        using (ZipFile zip = ZipFile.Read(LocalCatalogZip))
        {
            zip["ListingExport.txt"].Extract(data);
        }
        data.Seek(0, SeekOrigin.Begin);
        return data;
    }

It's not the library you're using now, but if you can change, you can get that functionality.


Here's a variation which would return a Dictionary<string,MemoryStream> of for the contents of every file of a zip file.

    private static Dictionary<string,MemoryStream> UnZipToMemory()
    {
        var result = new Dictionary<string,MemoryStream>();
        using (ZipFile zip = ZipFile.Read(LocalCatalogZip))
        {
            foreach (ZipEntry e in zip)
                            {
                                MemoryStream data = new MemoryStream();
                                e.Extract(data);
                                result.Add(e.FileName, data);
                            }
        }
        return result;
    }
Comments