0 votes
by (120 points)

I'm creating files using a Streamwriter.
I directly want to add the content into a zip and won't create a temporay file.

This ist possible with the System.IO.Compression ZipArchive:

using (var zipStream = new FileStream("archive.zip", FileMode.Create))
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
   ZipArchiveEntry entry = zip.CreateEntry("file.txt");
   using (var writer = new StreamWriter(entry.Open()))
   {
      writer.WriteLine("Hello Zip");
   }
}

Is this possible with your ZipArchive?
I don't get the right direction.

Sincerly
Daniel Hüttenberger

Applies to: Rebex ZIP

1 Answer

0 votes
by (70.2k points)

Unfortunately, this functionality is currently not supported.

However, you can achieve similar result by storing your content in the memory stream, then add the whole memory stream into the ZipArchive like this:

using (var zipStream = new FileStream("archive.zip", FileMode.Create))
using (var zip = new ZipArchive(zipStream))
{
    var memory = new MemoryStream();
    using (var writer = new StreamWriter(memory, new UTF8Encoding(false, true), 1024, true))
    {
        writer.WriteLine("Hello Zip");
    }

    memory.Position = 0;
    zip.AddFile(memory, "file.txt");
}

In case the data is huge and cannot be stored in memory, a workaround still exists. You can use producer-consumer algorithm to write data into shared stream in one thread and read the data from the shared stream in second thread.
The second thread just performs zip.AddFile(sharedStream, "file.txt"); while the first stream is performing sharedStream.Write() operations.

If you want a sample code for such solution, please let us know here.

...