Learn how to create flat ZIP archives in C# .NET: https://blog.aspose.com/2022/01/17/create-a-flat-zip-archive-in-csharp/
Last active
January 18, 2022 04:45
-
-
Save aspose-com-gists/32d7cf09b1c47c4cddafcb0ca30d0436 to your computer and use it in GitHub Desktop.
Create a Flat ZIP Archive in C# .NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load ZIP archive | |
using (Archive outer = new Archive("Archives/nested-archive.zip")) | |
{ | |
// Create a list to delete inner ZIP entries after extraction | |
List<ArchiveEntry> entriesToDelete = new List<ArchiveEntry>(); | |
// Create a list to add names of files in inner ZIP archives | |
List<string> namesToInsert = new List<string>(); | |
// Create a list to add stream objects of files in inner ZIP archives | |
List<MemoryStream> contentToInsert = new List<MemoryStream>(); | |
// Loop through entries in the parent ZIP | |
foreach (ArchiveEntry entry in outer.Entries) | |
{ | |
// Check if entry is a ZIP file | |
if (entry.Name.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
// Add entry to list to keep reference in order to remove it from the archive later | |
entriesToDelete.Add(entry); | |
// Create stream object to open the ZIP archive | |
MemoryStream innerCompressed = new MemoryStream(); | |
entry.Open().CopyTo(innerCompressed); | |
// Load the ZIP archive from stream object | |
using (Archive inner = new Archive(innerCompressed)) | |
{ | |
// Loop over entries of archive | |
foreach (ArchiveEntry ie in inner.Entries) | |
{ | |
// Keep the name of entry in list | |
namesToInsert.Add(ie.Name); | |
// Extract archive entry into a stream object | |
MemoryStream content = new MemoryStream(); | |
ie.Open().CopyTo(content); | |
// Add entry to the list | |
contentToInsert.Add(content); | |
} | |
} | |
} | |
} | |
// Delete the inner ZIP archives | |
foreach (ArchiveEntry e in entriesToDelete) | |
outer.DeleteEntry(e); | |
// Insert the files of inner ZIP archives to parent ZIP archive | |
for (int i = 0; i < namesToInsert.Count; i++) | |
outer.CreateEntry(namesToInsert[i], contentToInsert[i]); | |
outer.Save("Archives/flatten.zip"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment