259

I'm trying to create a ZIP archive with a simple demo text file using a MemoryStream as follows:

using (var memoryStream = new MemoryStream())
using (var archive = new ZipArchive(memoryStream , ZipArchiveMode.Create))
{
    var demoFile = archive.CreateEntry("foo.txt");

    using (var entryStream = demoFile.Open())
    using (var streamWriter = new StreamWriter(entryStream))
    {
        streamWriter.Write("Bar!");
    }

    using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
    {
        stream.CopyTo(fileStream);
    }
}

If I run this code, the archive file itself is created but foo.txt isn't.

However, if I replace the MemoryStream directly with the file stream, the archive is created correctly:

using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
using (var archive = new ZipArchive(fileStream, FileMode.Create))
{
    // ...
}

Is it possible to use a MemoryStream to create the ZIP archive without the FileStream?

2

11 Answers 11

425

Thanks to ZipArchive creates invalid ZIP file, I got:

using (var memoryStream = new MemoryStream())
{
   using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
   {
      var demoFile = archive.CreateEntry("foo.txt");

      using (var entryStream = demoFile.Open())
      using (var streamWriter = new StreamWriter(entryStream))
      {
         streamWriter.Write("Bar!");
      }
   }

   using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
   {
      memoryStream.Seek(0, SeekOrigin.Begin);
      memoryStream.CopyTo(fileStream);
   }
}

That indicated we need to call Dispose on ZipArchive before we can use it, which as Amir suggests is likely because it writes final bytes like checksum to the archive that makes it complete. But in order not close the stream so we can re-use it after you need to pass true as the third parameter to ZipArchive.

4
  • 1
    Good solution for both desktop and web API Commented Oct 26, 2022 at 2:45
  • Is there a pair of curly brackets missing after using (var entryStream = demoFile.Open())? I think the using (var streamWriter = new StreamWriter(entryStream)) stuff should be inside the entryStream using clause...
    – mbd
    Commented Mar 19 at 14:58
  • @mbd it's optional (similar to if statements) if you omit the brackets then the stream is disposed after the next line vs the code block if you use brackets.
    – Michael
    Commented Apr 1 at 10:00
  • You're right, @Michael, thanks for the answer, i didn't notice that "using (var streamWriter....) {} was considered as one command and so, inside the using (var entrystream...) scope.
    – mbd
    Commented Apr 2 at 9:20
126

Just another version of zipping without writing any file.

string fileName = "export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
byte[] fileBytes = here is your file in bytes
byte[] compressedBytes;
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

using (var outStream = new MemoryStream())
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(fileBytes))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
    compressedBytes = outStream.ToArray();
}
0
22

Set the position of the stream to the 0 before copying it to the zip stream.

using (var memoryStream = new MemoryStream())
{
   using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
   {
         var demoFile = archive.CreateEntry("foo.txt");

         using (var entryStream = demoFile.Open())
         using (var streamWriter = new StreamWriter(entryStream))
         {
             streamWriter.Write("Bar!");
          }
   }

    using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
    {
         memoryStream.Position=0;
         memoryStream.WriteTo(fileStream);
    }
 }
1
  • Thanks for the straightforward solution. kudos!! Commented Oct 15, 2021 at 12:20
18

Working solution for MVC

public ActionResult Index()
{
    string fileName = "test.pdf";
    string fileName1 = "test.vsix";
    string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

    byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\test\test.pdf");
    byte[] fileBytes1 = System.IO.File.ReadAllBytes(@"C:\test\test.vsix");
    byte[] compressedBytes;
    using (var outStream = new MemoryStream())
    {
        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
        {
            var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
            using (var entryStream = fileInArchive.Open())
            using (var fileToCompressStream = new MemoryStream(fileBytes))
            {
                fileToCompressStream.CopyTo(entryStream);
            }

            var fileInArchive1 = archive.CreateEntry(fileName1, CompressionLevel.Optimal);
            using (var entryStream = fileInArchive1.Open())
            using (var fileToCompressStream = new MemoryStream(fileBytes1))
            {
                fileToCompressStream.CopyTo(entryStream);
            }
        }
        compressedBytes = outStream.ToArray();
    }
    return File(compressedBytes, "application/zip", fileNameZip);
}
4
  • 4
    The Controller.File method has an overload that accepts Stream. Use that to avoid creating yet another copy of a ZIP file in memory. Commented Aug 28, 2019 at 14:27
  • 1
    This solution works perfect! Thanks! You don't even need to move byte arrays (byte[]). Just use a MemoryStream and don't forget to seek zero before you return the result back (.Seek(0, SeekOrigin.Begin);)
    – Tolbxela
    Commented Mar 22, 2021 at 17:46
  • Can confirm this works for me in donet core 5.* w/ WebApi.
    – Michael K
    Commented Sep 1, 2021 at 12:55
  • Works in .net 7 also
    – Luis Lopez
    Commented Mar 16, 2023 at 11:30
6

You need to finish writing the memory stream then read the buffer back.

        using (var memoryStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create))
            {
                var demoFile = archive.CreateEntry("foo.txt");

                using (var entryStream = demoFile.Open())
                using (var streamWriter = new StreamWriter(entryStream))
                {
                    streamWriter.Write("Bar!");
                }
            }

            using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
            {
                var bytes = memoryStream.GetBuffer();
                fileStream.Write(bytes,0,bytes.Length );
            }
        }
3
using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program`enter code here`
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}
3

I'm late to the party, but there are scenarios where you can't access the ZipArchive's constructor to set the leaveOpen parameter and where you don't want the ZIP to be written to disk. In my case, the AsiceArchive class I'm using internally creates a ZipArchive but doesn't set leaveOpen to true.

I created a subclass of Stream that delegates all calls to an inner stream (a few clicks with ReSharper). This class is not disposable, so when the ZipArchive gets disposed, nothing happens to the inner stream.

public class NondisposingStreamWrapper : Stream
{
    private readonly Stream _streamImplementation;

    public NondisposingStreamWrapper(Stream inner) => _streamImplementation = inner;

    public override void Flush() => _streamImplementation.Flush();

    public override int Read(byte[] buffer, int offset, int count) => _streamImplementation.Read(buffer, offset, count);

    public override long Seek(long offset, SeekOrigin origin) => _streamImplementation.Seek(offset, origin);

    public override void SetLength(long value) => _streamImplementation.SetLength(value);

    public override void Write(byte[] buffer, int offset, int count) => _streamImplementation.Write(buffer, offset, count);

    public override bool CanRead => _streamImplementation.CanRead;

    public override bool CanSeek => _streamImplementation.CanSeek;

    public override bool CanWrite => _streamImplementation.CanWrite;

    public override long Length => _streamImplementation.Length;

    public override long Position
    {
        get => _streamImplementation.Position;
        set => _streamImplementation.Position = value;
    }
}

Use it like this:

using var memoryStream = new MemoryStream();
var output = new NondisposingStreamWrapper(memoryStream);

using (var archive = new ZipArchive(output, ZipArchiveMode.Create))
{
    // add entries to archive
}

memoryStream.Flush();
memoryStream.Position = 0;

// write to file just for testing purposes
File.WriteAllBytes("out.zip", memoryStream.ToArray());
0
2

Function to return stream that contain zip file

public static Stream ZipGenerator(List<string> files)
{
    ZipArchiveEntry fileInArchive;
    Stream entryStream;
    int i = 0;
    List<byte[]> byteArray = new List<byte[]>();

    foreach (var file in files)
    {
        byteArray.Add(File.ReadAllBytes(file));
    }

    var outStream = new MemoryStream();
    
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        foreach (var file in files)
        {
            fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));

            using (entryStream = fileInArchive.Open())
            {
                using (var fileToCompressStream = new MemoryStream(byteArray[i]))
                {
                    fileToCompressStream.CopyTo(entryStream);
                }
                i++;
            }
        }
    }
    outStream.Position = 0;
    return outStream;
}

If you want , write zip to file stream.

using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\test.zip", FileMode.Create))
{
   outStream.Position = 0;
   outStream.WriteTo(fileStream);
}

`

4
  • Reading all files into memory first is huge waste of memory. You end up with all files twice in memory. Once in the byteArray and once in the ZipArchive. Not to mention that you do not need to load files to memory at all. Use streaming, as shown in all the other existing answers. Commented Dec 12, 2019 at 12:31
  • @MartinPrikryl Question is way to write zip file into memory. thats why i use memory . of course the best way is write into local
    – Arun C S
    Commented Dec 12, 2019 at 13:34
  • I know what question is about. The point of my comment is that your implementation of creating a ZIP file in memory is hugely inefficient. The implementations in other answers are better. Commented Dec 12, 2019 at 14:01
  • 1
    As with any code on StackOverflow, this code must be refactored to suit your needs. After trying the solutions outlined in the other answers to no avail, I was able to get a solution from this answer quickly, then refactor the code to take out the redundancies. Commented Apr 22, 2022 at 17:07
1

For me something like this was ok:

using (var memoryStream = new MemoryStream())
{
   using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
   {
      var file = archive.CreateEntry("file.json");
      using var entryStream = file.Open();
      using var streamWriter = new StreamWriter(entryStream);
      streamWriter.WriteLine(someJsonLine);
   }
}
0
1

Just in case, if anyone wants to save a dynamic zip file through SaveFileDialog.

var logFileName = "zip_filename.zip";
appLogSaver.FileName = logFileName;
appLogSaver.Filter = "LogFiles|*.zip";
appLogSaver.DefaultExt = "zip";
DialogResult resDialog = appLogSaver.ShowDialog();

if (resDialog.ToString() == "OK")
{
    System.IO.FileStream fs = (System.IO.FileStream)appLogSaver.OpenFile();

    using (var memoryStream = new MemoryStream())
    {
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            var demoFile = archive.CreateEntry("foo.txt");
            using (var entryStream = demoFile.Open())
            {
                using (var streamWriter = new StreamWriter(entryStream))
                {
                    //read your existing file and put the content here 
                    streamWriter.Write("Bar!");
                }
            }

            var demoFile2 = archive.CreateEntry("foo2.txt");
            using (var entryStream = demoFile2.Open())
            {
                using (var streamWriter = new StreamWriter(entryStream))
                {
                    streamWriter.Write("Bar2!");
                }
            }
        }

        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fs);
    }
    fs.Close();
}
-1

This is the way to convert a entity to XML File and then compress it:

private  void downloadFile(EntityXML xml) {

string nameDownloadXml = "File_1.xml";
string nameDownloadZip = "File_1.zip";

var serializer = new XmlSerializer(typeof(EntityXML));

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=" + nameDownloadZip);

using (var memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        var demoFile = archive.CreateEntry(nameDownloadXml);
        using (var entryStream = demoFile.Open())
        using (StreamWriter writer = new StreamWriter(entryStream, System.Text.Encoding.UTF8))
        {
            serializer.Serialize(writer, xml);
        }
    }

    using (var fileStream = Response.OutputStream)
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

Response.End();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.