简体   繁体   English

如何从 C# 中的文件创建内存中的结构化 ZIP 存档?

[英]How to create an in-memory structured ZIP archive from files in C#?

I have a number of files belonging to some logical category, say, "Category_A", and a number of other files belonging to a different logical category ("Category_B").我有一些属于某个逻辑类别的文件,比如“Category_A”,还有一些属于不同逻辑类别(“Category_B”)的其他文件。 I would like to create an in-memory ZIP object (MemoryStream, or byte array, or something else) so that the resulting structure of the ZIP object reflects the following scheme:我想创建一个内存中的 ZIP 对象(MemoryStream、字节数组或其他东西),以便 ZIP 对象的结果结构反映以下方案:

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

Directories "Category_A" and "Category_B" do not exist in the source file system, and the files come from different places.源文件系统中不存在目录“Category_A”和“Category_B”,文件来自不同的地方。

Is there some possibility to achieve this with any library?有没有可能用任何图书馆来实现这一点? (My project is in .Net 4.0, upgrading is no option). (我的项目是在 .Net 4.0 中,升级是没有选择的)。 I tried with the IonicZip Zip File and GZipStream, but did not find a solution.我尝试使用 IonicZip Zip 文件和 GZipStream,但没有找到解决方案。

Thanks everybody.谢谢大家。 In the mean time, I have found an answer myself (through try and error, as usual).与此同时,我自己也找到了答案(像往常一样,通过尝试和错误)。 Using Ionic Zip library, you do approximately this:使用 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");

My error while trying previously was that I first created ZipEntries for the categories and then additionally for their files which is wrong, since an empty ZipEntry is then created with the name of the category.我之前尝试时的错误是我首先为类别创建了 ZipEntries,然后另外为它们的文件创建了错误,因为然后使用类别名称创建了一个空的 ZipEntry。

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

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