【发布时间】:2012-12-10 19:26:00
【问题描述】:
我一直在开发一种工具,该工具使用SharpZipLib 将文件添加到压缩文件中,并针对ZipEntry 进行评论以存储我需要的一段元数据。 (我知道还有其他方法可以处理这些元数据,但如果可以避免,我想避免重新构建我的解决方案。)
用于将文件和元数据写入 zipfile 的 [略微简化] 代码如下:
public static void AddFileToZip(string path, Guid metadata)
{
using (ZipFile zipFile = new ZipFile(__zipName))
{
zipFile.BeginUpdate();
zipFile.Add(path);
zipFile.CommitUpdate();
zipFile.Close();
}
// Close and reopen the ZipFile so it can find the ZipEntry:
using (ZipFile zipFile = new ZipFile(__zipName))
{
string cleanPath = ZipEntry.CleanName(path);
zipFile.BeginUpdate();
zipFile.GetEntry(cleanPath).Comment = metadata.ToString("N");
zipFile.CommitUpdate();
zipFile.Close();
}
}
为此的测试工具,然后读取:
[Test]
public void ArchiveCreationTests()
{
// Hard-code some variables
string testFile = @"C:\Users\owen.blacker\Pictures\Ddraig arian.png";
Guid guid = Guid.NewGuid();
MyClassName.AddFileToZip(testFile, guid);
Assert.IsTrue(File.Exists(__zipName), "File does not exist: " + __zipName);
string cleanName = ZipEntry.CleanName(testFile);
ZipFile zipfile = new ZipFile(__zipName);
Assert.GreaterOrEqual(
zipfile.FindEntry(cleanName, true),
0,
"Cannot file ZipEntry " + cleanName);
ZipEntry zipEntry = zipfile.GetEntry(cleanName);
StringAssert.AreEqualIgnoringCase(
guid.ToString("N"),
zipEntry.Comment,
"Cannot validate GUID comment.");
}
现在我的 zipfile 正在创建——它确实包含我的测试图像 Ddraig arian.png——,ZipEntry 被成功找到,但 StringAssert 调用总是失败。我不完全确定它失败是因为它没有被写入,还是它失败是因为它没有被读取。
现在我知道你必须使用ZipFile/ZipEntry 来访问ZipEntry.Comment,就像ZipInputStream doesn't let you get to the Comment,但我am使用ZipFile 和ZipEntry,所以我不明白为什么它不起作用。
有人有什么想法吗?
(AddFileToZip 中稍微奇怪的关闭并重新打开是因为 ZipFile.GetEntry 调用总是失败,大概是因为 ZipEntry 尚未写入文件索引。是的,我的测试文件确实是silver dragon。)
【问题讨论】:
标签: c# zip sharpziplib