Search code examples
c#.netzip

Renaming a .Zip entry using only C# / .NET?


So what I'm trying to do right now is opening a .Zip file and renaming a file inside it (.NET 4.6.1). I don't think I'm allowed to use third-party libraries since this is a very simple operation (or so I thought, because I couldn't find any MSDN function to rename entries).

I found a couple of ways, but they are nasty. You can extract the file to disk and add it again with a different name, or you can also create a new entry with the new name in the zip, copy the file through a stream, and delete the original entry.

Is there any effective way to do this? I don't mind any ideas at this point. I know that with DotNetZip its only one line but I can't use a third part library.

Thanks a lot for the help!


Solution

  • Using the ZipArchive in System.IO.Compression. Here is an example that adds a .dat extension to every entry in the specified zip file:

    private static void RenameZipEntries(string file)
    {
        using (var archive = new ZipArchive(File.Open(file, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update))
        {
            var entries = archive.Entries.ToArray();
            foreach (var entry in entries)
            {
                var newEntry = archive.CreateEntry(entry.Name + ".dat");
                using (var a = entry.Open())
                using (var b = newEntry.Open())
                    a.CopyTo(b);
                entry.Delete();
            }
        }
    }