0

I am trying to write a compressed xml data to a memory stream. Here is my test console app code:

var ms = new MemoryStream();
var gstream = new GZipStream(ms, CompressionMode.Compress);

var settings = new XmlWriterSettings();
settings.Indent = true;

var writer = XmlWriter.Create(gstream, settings);
writer.WriteStartElement("x", "root", "123");
writer.WriteStartElement("item");
writer.WriteAttributeString("xmlns", "x", null, "abc");
writer.WriteEndElement();
writer.WriteEndElement();            

Console.WriteLine("Data length: " + ms.ToArray().Length);

writer.Close();
gstream.Close();
ms.Close();    

Console.ReadLine();

And the output is:

Data length: 0

What am i doing wrong? Thank you.

1 Answers1

0

You must close the writer to flush the stream. Just change the code to:

writer.Close();
gstream.Close();
ms.Close();   

Console.WriteLine("Data length: " + ms.ToArray().Length);

and it should work.

matiash
  • 54,791
  • 16
  • 125
  • 154