gpt4 book ai didi

c# - 将 updateEntry() 方法与 dotnetzip 一起使用不会正确覆盖文件

转载 作者:行者123 更新时间:2023-11-30 15:35:06 28 4
gpt4 key购买 nike

我最近遇到了一些问题。我一直在尝试将一个 zip 文件提取到内存流中,然后从该流中使用 updateEntry() 方法将其添加到目标 zip 文件中。

问题是,当流中的文件被放入目标 zip 时,如果文件不在 zip 中,它就会工作。如果存在同名文件,则不会正确覆盖。它在 dotnetzip 文档上说,此方法将覆盖 zip 中存在的同名文件,但它似乎不起作用。它会正确写入,但是当我去检查 zip 时,应该被覆盖的文件的压缩字节大小为 0,这意味着出现了问题。

我在下面附上我的代码,向您展示我在做什么:

ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);

using(zipnew) {
foreach(ZipEntry zenew in zipnew) {
percent = (current / zipnew.Count) * 100;
string flna = zenew.FileName;
var fstream = new MemoryStream();

zenew.Extract(fstream);
fstream.Seek(0, SeekOrigin.Begin);

using(zipold) {
var zn = zipold.UpdateEntry(flna, fstream);
zipold.Save();
fstream.Dispose();
}
current++;
}
zipnew.Dispose();
}

最佳答案

虽然可能有点慢,但我找到了解决办法,手动删除并添加文件。我会把代码留在这里,以防其他人遇到这个问题。

ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);

using(zipnew) {
// Loop through each entry in the zip file
foreach(ZipEntry zenew in zipnew) {
string flna = zenew.FileName;

// Create a new memory stream for extracted files
var ms = new MemoryStream();


// Extract entry into the memory stream
zenew.Extract(ms);
ms.Seek(0, SeekOrigin.Begin); // Rewind the memory stream

using(zipold) {
// Remove existing entry first
try {
zipold.RemoveEntry(flna);
zipold.Save();
}
catch (System.Exception ex) {} // Ignore if there is nothing found

// Add in the new entry
var zn = zipold.AddEntry(flna, ms);
zipold.Save(); // Save the zip file with the newly added file
ms.Dispose(); // Dispose of the stream so resources are released
}
}
zipnew.Dispose(); // Close the zip file
}

关于c# - 将 updateEntry() 方法与 dotnetzip 一起使用不会正确覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15355389/

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