Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip Archive: Can I rename or move a ZipArchiveEntry?

Tags:

c#

.net

zip

Does the .NET ZipArchive allow to rename or move entries? Currently it's not possible to change the name of a ZipArchiveEntry once it is created. It seems that I have to copy the stream of the original ZipArchiveEntry to a newly ZipArchiveEntry with the changed name.

Thanks Martin

like image 449
msedi Avatar asked May 31 '15 20:05

msedi


People also ask

Can you rename files in a zip folder?

For large Zip files, it may be faster to rename a number of files as a batch. Select multiple files and/or folders; then press F2. A dialog will display with a list of the selected files and folders. Next, rename each file or folder by clicking on it and typing in the new name.

How does ZipArchive work?

Extension MethodsArchives a file by compressing it and adding it to the zip archive. Archives a file by compressing it using the specified compression level and adding it to the zip archive. Extracts all the files in the zip archive to a directory on the file system.

What is ZIP archive in C#?

Add Files or Folders to ZIP Archives Programmatically in C# April 22, 2020 · 5 min · Usman Aziz. The ZIP archives are used to compress and keep one or more files or folders into a single container. A ZIP archive encapsulates the files and folders as well as holds their metadata information.


1 Answers

I don't know what "move" would mean, other than to rename an entry. Even in regular disk file systems, a "move" really is just a rename where the full path of the file name has changed, not just the "leaf node" file name. In a .zip archive, this is even more explicit; a "directory" or "folder" in an archive exists only by virtue of an entry having that directory name in its name (separated, of course, by a directory separator character). So "move" is exactly the same as "rename".


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

Code to do that would 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 above, you can call like this:

ZipArchive archive = ...; open archive in "update" mode
string oldName = ...,
    newName = ...; // names initialized as appropriate

archive.RenameEntry(oldName, newName);
like image 70
Peter Duniho Avatar answered Sep 27 '22 18:09

Peter Duniho