【问题标题】:How to create an in-memory structured ZIP archive from files in C#?如何从 C# 中的文件创建内存中结构化的 ZIP 存档?
【发布时间】:2020-04-30 07:39:44
【问题描述】:

我有一些属于某个逻辑类别的文件,例如“Category_A”,以及一些属于不同逻辑类别(“Category_B”)的其他文件。我想创建一个内存 ZIP 对象(MemoryStream,或字节数组,或其他东西),以便 ZIP 对象的结果结构反映以下方案:

ZIP
 +-Category_A
 |    +FileA1
 |    +FileA2
 |      ...
 +-Category_B
      +FileB1
      +FileB2
       ...

源文件系统中不存在目录“Category_A”和“Category_B”,文件来自不同的地方。

是否有可能使用任何库来实现这一点? (我的项目在 .Net 4.0 中,无法升级)。我尝试使用 IonicZip Zip 文件和 GZipStream,但没有找到解决方案。

【问题讨论】:

  • 为什么不使用临时目录?然后从中创建一个文件流?
  • 如何使用这个流?您似乎允许多种选择,它真的必须是一个文件吗?拉链?
  • 这能回答你的问题吗? How to create ZipArchive from files in memory in C#? 您可以将文件夹名称放在CreateEntryFromFile 方法参数中,例如CreateEntryFromFile("CategoryB\\"+filename。这将在 zip 存档中创建文件夹 CategoryB

标签: c# zip


【解决方案1】:

谢谢大家。同时,我自己也找到了答案(像往常一样通过尝试和错误)。使用 Ionic Zip 库,您可以这样做:

ZipFile zip = new ZipFile();

// below are the files of "Category_A" converted to byte arrays: 
byte[] fileA1   = ...;
byte[] fileA2   = ...;

// the byte arrays will be added to the archive with paths "Category_A\\fileA1" 
// and "Category_A\\fileA2" respectively. 
// The level "Category_A" within the archive is created automatically.
zip.AddEntry("Category_A\\fileA1", fileA1);
zip.AddEntry("Category_A\\fileA2", fileA2);

// The same for "Category_B" and its files:
byte[] fileB1   = ...;
byte[] fileB2   = ...;

zip.AddEntry("Category_B\\fileB1", fileB1);
zip.AddEntry("Category_B\\fileB2", fileB2);

// save the result.
zip.Save("test.zip");

我之前尝试的错误是我首先为类别创建了 ZipEntry,然后又为它们的文件创建了错误的,因为随后使用类别名称创建了一个空的 ZipEntry。

【讨论】:

  • 它们不需要是字节数组,流也可以(只是一个注释)。
猜你喜欢
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2022-06-24
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多