简体   繁体   English

C#使用zip存档System.IO.Compression创建zip文件

[英]C# create zip file using zip archive System.IO.Compression

Here is the functionality I want to achieve 这是我想要实现的功能

  • Write a JSON file. 写一个JSON文件。
  • Write a PDF file. 写一个PDF文件。
  • Create an archive for these two files 为这两个文件创建存档

I am using the System.IO.Compression ZipArchive to achieve this. 我正在使用System.IO.Compression ZipArchive来实现这一目标。 From the documentation, I have not found a good use case for this. 从文档中,我没有找到一个很好的用例。 The examples in documentation assume that the zip file exists. 文档中的示例假定zip文件存在。

What I want to do Create zipArchive stream write JSON file and pdf file as entries in the zip file. 我想做什么创建zipArchive流将JSON文件和pdf文件写为zip文件中的条目。

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);
     }
   }
 }

You don't close the stream , you open with ' manifest.Open() '. 你没有关闭stream ,你打开' manifest.Open() '。 Then it might not have written everything to the zip. 然后它可能没有写入zip的所有内容。

Wrap it in another using , like this: 用另一种using包装它,如下所示:

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);
         }
     }
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM