Editing zip file using Aspose.zip


#1

We have a project requirement, in which we need to edit the zip file on the fly without extracting it on the disk. For example, we have nested zip files and we need to extract the nested zip file’s contents into the parent zip file. Can anyone please provide me an example if it is possible with Aspose.zip?


#2

@meenal,

We have logged your requirement in our issue tracking system. Your ticket number is ZIPNET-393. We will further look into the details of this requirement and will keep you updated on the status of the linked issue.


#3

@meenal,

Please check the following code and let us know if this helps you in achieving what you are looking for?

using (Archive outer = new Archive("outer.zip"))
{
    List<ArchiveEntry> entriesToDelete = new List<ArchiveEntry>();
    List<string> namesToInsert = new List<string>();
    List<MemoryStream> contentToInsert = new List<MemoryStream>();

    foreach (ArchiveEntry entry in outer.Entries)
    {
        if (entry.Name.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase) /* or another condition */ ) // Find an entry which is an archive itself
        {
            entriesToDelete.Add(entry); // Keep reference to the entry in order to remove it from the archive later
            MemoryStream innerCompressed = new MemoryStream();
            entry.Open().CopyTo(innerCompressed); //This extracts the entry to a memory stream

            using (Archive inner = new Archive(innerCompressed)) // We know that content of the entry is an zip archive so we may extract
            {
                foreach (ArchiveEntry ie in inner.Entries) // Loop over entries of inner archive
                {
                    namesToInsert.Add(ie.Name); // Keep the name of inner entry.
                    MemoryStream content = new MemoryStream();
                    ie.Open().CopyTo(content);
                    contentToInsert.Add(content); // Keep the content of inner entry.
                }
            }
        }
    }

    foreach (ArchiveEntry e in entriesToDelete) { outer.DeleteEntry(e); } // Delete all the entries which are archives itself

    for (int i = 0; i < namesToInsert.Count; i++)
    {
        outer.CreateEntry(namesToInsert[i], contentToInsert[i]); // Adds entries which were entries of inner archives
    }

    outer.Save("flatten.zip");
}

So, to flatten an archive we extract inner archives into a memory and remove them later. We keep content of inner entries within memory streams too, so memory consumption may be higher. It is also possible to save archive to the same path i.e. outer.Save("outer.zip"); but it is better to save to another, because saving to the same involves copying to temporary file.