Add contents of a stream to a Zip file

by CameronM 19. May 2016 04:05

In a recent project I needed to create a Zip file containing a number of files and a summary of the contents. Thanks to the .NET 4.5 ZipArcive class, this was relatively straigh forward.

One hurdle that needed to be overcome was adding the a text file to the Zip that contained a list of the files that had been Zipped along with some other information about each record. I started by creating a StreamWriter, using a MemoryStream as I didn't actually want to save the file to disk.

Lines containiing the file details would be written to the StreamWriter as each record was processed, then at the end of the process, the MemoryStream would be saved to the ZipArchive.

// create and save zip file
using (var outStream = new MemoryStream())
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    MemoryStream ms = new MemoryStream();
    var csv = new StreamWriter(ms);

    // call some process on each record sent into the function
    foreach (var graphic in Request.Items)
        // write results to stream

    // add results to the zip
    var csvCompressed = archive.CreateEntry(Request.Record.BatchName + ".txt");
    using (var csvStream = csvCompressed.Open())
        csv.Flush(); // write content to memory stream
        ms.Seek(0, SeekOrigin.Begin);
        ms.CopyTo(csvStream); // save memory stream to Zip

    // save the zip file
    using (var fileStream = new FileStream(fullPath, FileMode.Create))
        outStream.Seek(0, SeekOrigin.Begin);