4

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);
     }
   }
 }
Nikhilesh
  • 1,711
  • 2
  • 15
  • 19
  • 1
    I think you are on a good track with using Stream-based methods rather than those based on an existing file. On a side note, one thing I'd recommend is not using StreamWriters, which are more for text files, but instead apply Stream.CopyTo method which copies binary data directly. https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto?view=netframework-4.7.2#System_IO_Stream_CopyTo_System_IO_Stream_ – Alice Oct 29 '18 at 20:28

1 Answers1

7

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);
         }
     }
   }
 }
Poul Bak
  • 10,450
  • 5
  • 32
  • 57