Reputation: 2989
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
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