2

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.

Francesca Y
  • 183
  • 1
  • 11
  • 2
    Why don't you use a temp directory? And then create a filestream out of that? – Markus Zeller Jan 13 '20 at 15:12
  • 1
    Does [this not work and why not?](https://carlrippon.com/zipping-up-files-from-a-memorystream/) – Fixation Jan 13 '20 at 15:15
  • How this stream will be used? You seems to allow wide range of options, does it really have to be a single file? zip? – Sinatr Jan 13 '20 at 15:15
  • Does this answer your question? [How to create ZipArchive from files in memory in C#?](https://stackoverflow.com/questions/29647570/how-to-create-ziparchive-from-files-in-memory-in-c) You can put folder name to the `CreateEntryFromFile` method parameter like `CreateEntryFromFile("CategoryB\\"+filename`. This will create folder `CategoryB` in zip archive – oleksa Jan 13 '20 at 15:37

1 Answers1

2

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.

Francesca Y
  • 183
  • 1
  • 11