I am trying to edit the XmlDocument file contained in a zip file:
var zip = new ZipArchive(myZipFileInMemoryStream, ZipArchiveMode.Update); var entry = zip.GetEntry("filenameToEdit"); using (var st = entry.Open()) { var xml = new XmlDocument(); xml.Load(st); foreach (XmlElement el in xml.GetElementsByTagName("Relationship")) { if(el.HasAttribute("Target") && el.GetAttribute("Target").Contains(".dat")){ el.SetAttribute("Target", path); } } xml.Save(st); }
After executing this code, the contained file does not change. IF instead of xml.Save(st); I am writing xml to disk, I got edited.
Why is the edited file not written to zip? How to fix it?
EDIT:
I updated the code:
var tmp = new MemoryStream(); using (var zip = new ZipArchive(template, ZipArchiveMode.Read, true)) { var entry = zip.GetEntry("xml"); using (var st = entry.Open()) { var xml = new XmlDocument(); xml.Load(st); foreach (XmlElement el in xml.GetElementsByTagName("Relationship")) { if (el.HasAttribute("Target") && el.GetAttribute("Target").Contains(".dat")) { el.SetAttribute("Target", path); } } xml.Save(tmp); } } using (var zip = new ZipArchive(template, ZipArchiveMode.Update, true)) { var entry = zip.GetEntry("xml"); using (var st = entry.Open()) { tmp.Position = 0; tmp.CopyTo(st); } }
Thus, the zip file is edited, but only works if the stream length is equal. If tmp shorter, the rest of st is still in the file ...
hints?
source share