Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

zip

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"). 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
 +-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.

Is there some possibility to achieve this with any library? (My project is in .Net 4.0, upgrading is no option). I tried with the IonicZip Zip File and GZipStream, but did not find a solution.

like image 913
Francesca Y Avatar asked Oct 22 '25 01:10

Francesca Y


1 Answers

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:

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.

like image 123
Francesca Y Avatar answered Oct 24 '25 16:10

Francesca Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!