Edit ZipArchive in .NET Memory

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?

+5
source share
1 answer

I use this code to create a Zip InMemory (using the DotNetZip Library):

  MemoryStream saveStream = new MemoryStream(); ZipFile arrangeZipFile = new ZipFile(); arrangeZipFile.AddEntry("test.xml", "content..."); arrangeZipFile.Save(saveStream); saveStream.Seek(0, SeekOrigin.Begin); saveStream.Flush(); // might be useless, because it in memory... 

After that, I have a valid Zip inside a MemoryStream. I'm not sure why I added Flush () - I would suggest that this is redundant.

To edit an existing Zip, you can read it in a MemoryStream and instead of creating a "new ZipFile ()" use the "new ZipFile (byteArray ...)"

0
source

Source: https://habr.com/ru/post/1246155/


All Articles