IngoB
IngoB

Reputation: 2989

.net ZipFile class: How to modify a text file within an archive?

Does anyone have an idea how to modify a text file within a zip archive using .net's ZipFile class? I mean without unzipping everything, modifying and zipping again. Reading the file is easy so far:

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? <<
    }
}

Upvotes: 0

Views: 40

Answers (1)

Sohaib Jundi
Sohaib Jundi

Reputation: 1664

No need to extract the file to begin with. You can do this:

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);
  }
}

Upvotes: 1

Related Questions