C# create zip file using zip archive System.IO.Compression

cnetziparchive

Here is the functionality I want to achieve

  • Write a JSON file.
  • Write a PDF file.
  • Create an archive for these two files

I am using the System.IO.Compression ZipArchive to achieve this. From the documentation, I have not found a good use case for this. The examples in documentation assume that the zip file exists.

What I want to do
Create zipArchive stream write JSON file and pdf file as entries in the zip file.

using (var stream = new FileStream(path, FileMode.Create))
{
   using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
   {
     ZipArchiveEntry manifest = archive.CreateEntry(filenameManifest);

     using (StreamWriter writerManifest = new StreamWriter(manifest.Open()))
     {
       writerManifest.WriteLine(JSONObject_String);
     }

     ZipArchiveEntry pdfFile = archive.CreateEntry(filenameManifest);
     using (StreamWriter writerPDF = new StreamWriter(pdfFile.Open()))
     {
       writerPDF.WriteLine(pdf);
     }
   }
 }

Best Answer

You don't close the stream, you open with 'manifest.Open()'. Then it might not have written everything to the zip.

Wrap it in another using, like this:

using (var stream = new FileStream(path, FileMode.Create))
{
   using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
   {
     ZipArchiveEntry manifest = archive.CreateEntry(filenameManifest);
     using (Stream st = manifest.Open())
     {
         using (StreamWriter writerManifest = new StreamWriter(st))
         {
            writerManifest.WriteLine(JSONObject_String);
         }
     }

     ZipArchiveEntry pdfFile = archive.CreateEntry(filenameManifest);
     using (Stream st = manifest.Open())
     {
         using (StreamWriter writerPDF = new StreamWriter(st))
         {
            writerPDF.WriteLine(pdf);
         }
     }
   }
 }
Related Topic