Search code examples
c#asp.netdotnetzip

Trying to save zip to stream


I'm trying to save streams of files to a Zip stream.

The code:

public static MemoryStream ZipFiles(Dictionary<string, byte[]> files)
{
    var output = new MemoryStream();
    using (var zip = new ZipFile())
    {
        foreach (var file in files)
        {
            var ms = new MemoryStream(file.Value);
            ms.Seek(0, SeekOrigin.Begin);
            zip.AddEntry(file.Key, ms);
            zip.Save(output);
        }
    }
    return output;
}

It was working, but now on the 2nd time of loop on zip.Save it's throwing a ZipException with message "Cannot read that as a ZipFile". InnerException "object reference not set to an instance of an object".

Any help would be great.


Solution

  • Try to use next code:

            var output = new MemoryStream();
            using (var zip = new ZipFile())
            {
                foreach (var file in files)
                {
                    var ms = new MemoryStream(file.Value);
                    ms.Seek(0, SeekOrigin.Begin);
                    zip.AddEntry(file.Key, ms);
    
                }
                zip.Save(output);
            }
            return output;