.net ZipFile类:如何修改存档中的文本文件?

时间:2019-07-10 19:06:53

标签: .net zipfile

有人知道如何使用.net的ZipFile类修改zip归档文件中的文本文件吗?我的意思是没有解压缩所有内容,而是再次进行修改和压缩。到目前为止,读取文件很容易:

using (var zip = ZipFile.Open("ExcelWorkbookWithMacros.xlsm", ZipArchiveMode.Update))
{
    var entry = zip.GetEntry("xl/_rels/workbook.xml.rels");
    if (entry != null)
    {
        var tempFile = Path.GetTempFileName();
        entry.ExtractToFile(tempFile, true);
        var content = File.ReadAllText(tempFile);

        content = content.Replace("xxx", ""); // THIS IS WHAT I NEED TO DO

        >> How to save back the archive? <<
    }
}

1 个答案:

答案 0 :(得分:1)

无需解压缩文件。您可以这样做:

string entryName = "some entry";
string contents = "";
var entry = zip.GetEntry(entryName);
if (entry != null)
{
  using(StreamReader streamReader = new StreamReader(entry.Open()))
  {
    contents = streamReader.ReadToEnd();
  }

  contents = contents.Replace("xxx", "");
  entry.Delete();
  entry = zip.CreateEntry(entryName);

  using(StreamWriter streamWriter = new StreamWriter(entry.Open()))
  {
    streamWriter.Write(contents);
  }
}