I am using the DotNetZip library to rename a file within a zip archive.
Here is the code I am using:
void RenameFile(string existingArchive, string oldName, string newName)
{
using (ZipFile zip = ZipFile.Read(existingArchive))
{
ZipEntry targetFile = zip.Entries.FirstOrDefault(f =>
f.FileName.ToLower() == oldName.ToLower());
//targetFile is not null.
targetFile.FileName = newName;
zip.Save();
}
}
The issue I'm having is that after the rename operation, the zip is corrupted. When I browse it using WinRAR, I have a duplicate entry for the file I renamed (both of the entries are identical, with the new name). When I try to extract it, WinRAR throws a CRC error on the two identical entries.
I've tried saving to a different filename, but without luck.
I am using v1.9.1.8 of the library (the reduced version).
Update:
Removing one of the duplicate entries after renaming seems to work and has no visible side effects. Still, a less hacky approach would be welcome.
void RenameFile(string existingArchive, string oldName, string newName)
{
using (ZipFile zip = ZipFile.Read(existingArchive))
{
ZipEntry targetFile = zip.Entries.FirstOrDefault(f =>
f.FileName.ToLower() == oldName.ToLower());
//targetFile is not null.
targetFile.FileName = newName;
//if the file was duplicated, remove one of the duplicates:
var dupFiles = zip.Where(f => f.FileName == newName).ToList();
if (dupFiles.Count > 1)
{
zip.RemoveEntries(dupFiles.Skip(1).ToList());
}
zip.Save();
}
}
Update 2:
As the answers suggest the source file might be the problem, I've uploaded a sample zip file (24kb) here
This is the code I am using to verify it suffers from this issue:
using (ZipFile zip = ZipFile.Read("test.zip"))
{
ZipEntry entry = zip.Entries.FirstOrDefault(e => Path.GetFileName(e.FileName) == "test.max");
entry.FileName = Path.Combine(Path.GetDirectoryName(entry.FileName), "newname.max");
zip.Save(@"test2.zip");
}