Search code examples
c#.netasp.net-mvczip.net-4.5

Create zip file from byte[]


I am trying to create a Zip file in .NET 4.5 (System.IO.Compression) from a series of byte arrays. As an example, from an API I am using I end up with a List<Attachment> and each Attachment has a property called Body which is a byte[]. How can I iterate over that list and create a zip file that contains each attachment?

Right now I am under the impression that I would have to write each attachment to disk and create the zip file from that.

//This is great if I had the files on disk
ZipFile.CreateFromDirectory(startPath, zipPath);
//How can I create it from a series of byte arrays?

Solution

  • After a little more playing around and reading I was able to figure this out. Here is how you can create a zip file (archive) with multiple files without writing any temporary data to disk:

    using (var compressedFileStream = new MemoryStream())
    {
        //Create an archive and store the stream in memory.
        using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false)) {
            foreach (var caseAttachmentModel in caseAttachmentModels) {
                //Create a zip entry for each attachment
                var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);
    
                //Get the stream of the attachment
                using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body))
                using (var zipEntryStream = zipEntry.Open()) {
                    //Copy the attachment stream to the zip entry stream
                    originalFileStream.CopyTo(zipEntryStream);
                }
            }
        }
    
        return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
    }