1

I would like to generate an xml file on the fly and compact it in a zip file.

I need to use the XmlDocument and the Ionic library (for compression).

As I could understand the method ZipFile.AddEntry should do this task,but for some reason the xml file is being generated with empty content inside the zip file. If instead of send it to MemoryStream I save it on disk, I can see the xml nodes.

Any idea, what I'm doing wrong?

        MemoryStream memoryStream = new MemoryStream();

        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement("users");
        xmlDoc.AppendChild(rootNode);

        XmlNode userNode = xmlDoc.CreateElement("user");
        XmlAttribute attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "42";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "John";
        rootNode.AppendChild(userNode);

        userNode = xmlDoc.CreateElement("user");
        attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "39";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "Jen";
        rootNode.AppendChild(userNode);

        //if (File.Exists(@"c:\temp\Teste\z.xml")) {
        //    File.Delete(@"c:\temp\Teste\z.xml");
        //}
        //xmlDoc.Save(@"c:\temp\Teste\z.xml"); -- it works


        xmlDoc.Save(memoryStream);

        if (File.Exists(@"c:\temp\Teste\z.zip")) {
            File.Delete(@"c:\temp\Teste\z.zip");
        }

        using (ZipFile zip = new ZipFile(@"c:\temp\Teste\z.zip")) {
            //zip.AddFile(@"C:\Temp\a.txt"); -- it works
            zip.AddEntry("z.xml", memoryStream);
            zip.Save();
        }

Thanks.

Alba
  • 75
  • 1
  • 9
  • Have you tried rewinding the stream before writing it to the zip file? http://stackoverflow.com/questions/2629612/writing-string-to-stream-and-reading-it-back-does-not-work – Dijkgraaf Nov 19 '15 at 19:16
  • I already tried the code below before/after xmlDoc.Save, is this what do you mean by rewinding? xmlStream.Flush(); xmlStream.Position = 0; – Alba Nov 19 '15 at 19:21
  • Yes, reset the stream position back to zero as per the answer I linked to e.g. memoryStream.Seek(0, SeekOrigin.Begin); – Dijkgraaf Nov 19 '15 at 19:23
  • Worked. I just add the memoryStream.Seek(0, SeekOrigin.Begin); after xmlDoc.Save(memoryStream); Thank you so much! – Alba Nov 19 '15 at 19:29

0 Answers0