我正在使用DotNetZip库来重命名zip存档中的文件。
下面是我使用的代码:
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();
}
}我遇到的问题是,在重命名操作之后,zip已经损坏。当我使用WinRAR浏览它时,我对重命名的文件有一个重复的条目(这两个条目都是相同的,具有新的名称)。当我试图提取它时,WinRAR会对两个相同的条目抛出一个CRC错误。
我试过保存到不同的文件名,但没有运气。
我使用的是库的v1.9.1.8 (精简版本)。
更新:
重命名后删除一个重复条目似乎有效,没有明显的副作用。尽管如此,我们还是欢迎采取一种不那么刺耳的做法。
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();
}
}更新2:
如答案所示,源文件可能是问题所在,我上传了一个示例zip文件(24 As ) 这里
这是我用来验证它受到此问题影响的代码:
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");
}发布于 2013-03-27 13:00:30
您的方法似乎是合理的,因此很可能在DotNetZip库中有一个bug。
但如果您查看DotNetZip CodePlex站点上的C#实例 (更新压缩存档部分),您将看到推荐的(?)在存档中重命名现有条目的方法是:
zip[oldName].FileName = newName;这意味着您的方法将更改为:
void RenameFile(string existingArchive, string oldName, string newName)
{
using (ZipFile zip = ZipFile.Read(existingArchive))
{
zip[oldName].FileName = newName;
zip.Save();
}
}从我的测试中可以看出,上述方法按照预期工作,indexer属性this[string fileName]似乎使不区分大小写的文件名匹配。
https://stackoverflow.com/questions/15601189
复制相似问题