gpt4 book ai didi

c# - 如何正确创建 ZipArchive?

转载 作者:行者123 更新时间:2023-11-30 13:02:07 29 4
gpt4 key购买 nike

我正在编写桌面 WPF 应用程序 (.Net Framework 4.5),其中一项任务是将多个文件保存到 zip 存档。我做了2种方法。首先创建 zip,其次从中读取。

    public static String GetFileContent(String zipPath, String entityName)
{
String retVal = String.Empty;

using (ZipArchive zipfile = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in zipfile.Entries)
{
if (entry.Name.ToLower() == entityName)
{
using (StreamReader s = new StreamReader(entry.Open()))
{
retVal = s.ReadToEnd();
break;
}
}
}
}

return retVal;
}

public static void SetArchive(String path, String zipName, Dictionary<String, String> files)
{
using (var fileStream = new FileStream(Path.Combine(path, zipName), FileMode.OpenOrCreate))
{
using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Create))
{
foreach (KeyValuePair<String, String> file in files)
{
var entry = zip.CreateEntry(file.Key, CompressionLevel.Optimal);
using (Stream s = entry.Open())
{
byte[] data = Encoding.UTF8.GetBytes(file.Value);
s.Write(data, 0, data.Length);
}
}
}
}
}

事情是创建了 zip 存档并且远程管理器和 WinRAR 可以打开它,但是当我使用第二种方法读取它的内容时,我不断得到

Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory. at System.IO.Compression.ZipArchive.ReadCentralDirectory() at System.IO.Compression.ZipArchive.get_Entries() at Microsoft.MCS.SPPal.Storage.StorageObject.GetFileContent(String zipPath, String entityName) in z:\Home Inc\Microsoft.MCS.SPPal\Microsoft.MCS.SPPal\Storage\StorageObject.cs:line 32 at Microsoft.MCS.SPPal.MainWindow..ctor() in z:\Home Inc\Microsoft.MCS.SPPal\Microsoft.MCS.SPPal\MainWindow.xaml.cs:line 48

作为实验的一部分,我在远程管理器中创建了新存档并使用 GetFileContent 方法将其打开,效果非常好。所以我认为错误应该在 SetArchive 方法中。

任何帮助都会很棒,现在是凌晨 3 点,我被困住了。

P.S:我知道代码设计很烂,它被重写了几十次。

最佳答案

我能够通过在 ZipArchive 超出 SetArchive() 方法的范围之前添加对 Dispose() 的显式调用来实现它。

zip.Dispose();

关于c# - 如何正确创建 ZipArchive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226092/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com