Zip Archive: Can I rename or move ZipArchiveEntry?

Does .NET ZipArchive Allow Rename or Move Entries? It is currently not possible to change the name of ZipArchiveEntry after creating it. It seems that I need to copy the source ZipArchiveEntry stream to the new ZipArchiveEntry with the changed name.

Thanks Martin

+7
c # zip
source share
1 answer

I don’t know what “move” would mean except to rename the entry. Even on ordinary disk file systems, “moving” is actually just a renaming, where the full path of the file name has been changed, and not just the file name of the “leaf node”. In the .zip archive, this is even more obvious; A “directory” or “folder” in an archive exists only by virtue of an entry that has that directory name in its name (separated, of course, by the directory separator character). So, "move" is exactly the same as "rename."


As far as you can rename things, no & hellip, ZipArchive , you will need to create a new entry that is a copy of the original, but with a new name, and then delete the original.

The code for this will look like this:

 static void RenameEntry(this ZipArchive archive, string oldName, string newName) { ZipArchiveEntry oldEntry = archive.GetEntry(oldName), newEntry = archive.CreateEntry(newName); using (Stream oldStream = oldEntry.Open()) using (Stream newStream = newEntry.Open()) { oldStream.CopyTo(newStream); } oldEntry.Delete(); } 

Implemented as an extension method, as described above, you can call it like this:

 ZipArchive archive = ...; open archive in "update" mode string oldName = ..., newName = ...; // names initialized as appropriate archive.RenameEntry(oldName, newName); 
+7
source share

All Articles