Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

zip

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!

like image 743
Gaspa79 Avatar asked May 05 '16 14:05

Gaspa79


1 Answers

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();
        }
    }
}
like image 118
a-ctor Avatar answered Sep 23 '22 20:09

a-ctor