gpt4 book ai didi

c# - 覆盖 ZipArchiveEntry 的内容

转载 作者:行者123 更新时间:2023-11-30 13:12:49 28 4
gpt4 key购买 nike

如何覆盖 ZipArchiveEntry 的内容?如果新文件内容比原始文件内容短,则以下使用 StreamWriterStringBuilder 的代码将失败,例如:

using System.IO.Compression;
//...
using (var archive = ZipFile.Open("Test.zip", ZipArchiveMode.Update))
{
StringBuilder document;
var entry = archive.GetEntry("foo.txt");//entry contents "foobar123"
using (StreamReader reader = new StreamReader(entry.Open()))
{
document = new StringBuilder(reader.ReadToEnd());
}

document.Replace("foobar", "baz"); //builder contents "baz123"

using (StreamWriter writer = new StreamWriter(entry.Open()))
{
writer.Write(document); //entry contents "baz123123", expected "baz123"
}
}

生成包含新旧内容混合的文件“baz123123”而不是预期的“baz123”。有没有办法在写入新内容之前丢弃 ZipArchiveEntry 的旧内容?
注意:我不想提取文件,我想更改存档的内容

最佳答案

另一种方法是 entry.Open() 流的 SetLength(document.Length)

using(var stream = entry.Open())
{
stream.SetLength(document.Length);
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(document); //entry contents "baz123"
}
}

关于c# - 覆盖 ZipArchiveEntry 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810169/

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