覆盖 ZipArchiveEntry 的内容 [英] Overwrite contents of ZipArchiveEntry

查看:23
本文介绍了覆盖 ZipArchiveEntry 的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I overwrite contents of a ZipArchiveEntry? Following code using StreamWriter with StringBuilder fails if the new file contents are shorter than the original ones, for example:

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 的旧内容?
注意:我不想提取文件,我想更改存档内容.

Produces file containing new and old contents mixed up "baz123123" instead of expected "baz123". Is there perhaps a way how to discard the old contents of ZipArchiveEntry before writing the new ones?
note: I do not want to extract the file, I would like to change contents of the archive.

推荐答案

更新存档意味着您要从存档中添加、移动或删除条目.

Updating the archive means you are either adding, moving or removing an entry from the archive.

考虑执行以下步骤.

  • 获取条目内容

  • Get the entry content

从存档中删除条目(记下名称/位置)

Remove the entry from the archive (take note of name/location)

根据需要修改内容.

将修改后的内容添加回存档.

Add modified content back to the archive.

这篇关于覆盖 ZipArchiveEntry 的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆