Delete Files from a Zip Archive
“I’ve been trying out the ZIP package that you guys have and for the most part it’s great. I do however have a question about folder manipulation. What I would like to be able to do is individually remove files from the zip and if the directory is empty I would like to remove the directory from the zip file. Is there any way to remove directories from the zip as I can’t seem to find a way to do this? Also, is there any way to move/append files into a directory or create a directory in the zip?”
The files contained within a .zip archive may or may not include a relative or absolute path. For example, it is possible to have a .zip with several “text.txt” files:
To delete one or more files from a .zip, iterate over the entries from 0 to zipObject.NumEntries-1. For each ZipEntry object, your code can examine the entryObject.FileName property (which may also include a subdirectory path) to determine if it should be deleted. If so, then call zipObject.DeleteEntry(entryObject) to remove the entry from the zipObject’s entries. Once all entries have been deleted, call WriteZip or WriteZipAndClose to re-write the .zip with the deleted entries removed.
When iterating from 0 to zipObject.NumEntries, you will iterate over both file and directory entries. The entryObject.IsDirectory property indicates whether the entry is a directory entry or not. Removing directory entries is the same as for files. (Note: Removing a directory entry does not remove all the files within that directory, it simply removes the explicit directory entry within the .zip)
To create a new explicit directory entry within a .zip, call zipObject.AppendNewDir. (Note: All methods that Append files/dirs do not affect the existing .zip until WriteZip or WriteZipAndClose is called.)
To “move” files into a sub-directory within the .zip, simply update the zipEntry.FileName property to include the new subdirectory. For example, change the zipEntry.FileName property from “test.txt” to “subdir1.test.txt”, then rewrite the .zip. (Don’t re-write the .zip after each zipEntry object is modified. Make all modifications (appends, deletes, zipEntry.FileName changes, etc.) and the rewrite with a single call to WriteZip/WriteZipAndClose.