Memory stream is empty

Summer picture Summer · May 25, 2011 · Viewed 7.5k times · Source

I need to generate a huge xml file from different sources (functions). I decide to use XmlTextWriter since it uses less memory than XmlDocument.

First, initiate an XmlWriter with underlying MemoryStream

MemoryStream ms = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(ms, new UTF8Encoding(false, false));
xmlWriter.Formatting = Formatting.Indented;

Then I pass the XmlWriter (note xml writer is kept open until the very end) to a function to generate the beginning of the XML file:

xmlWriter.WriteStartDocument();

xmlWriter.WriteStartElement();

// xmlWriter.WriteEndElement(); // Do not write the end of root element in first function, to add more xml elements in following functions

xmlWriter.WriteEndDocument();
xmlWriter.Flush();

But I found that underlying memory stream is empty (by converting byte array to string and output string). Any ideas why?

Also, I have a general question about how to generate a huge xml file from different sources (functions). What I do now is keeping the XmlWriter open (I assume the underlying memory stream should open as well) to each function and write. In the first function, I do not write the end of root element. After the last function, I manually add the end of root element by:

string endRoot = "</Root>";
byte[] byteEndRoot = Encoding.ASCII.GetBytes(endRoot);
ms.Write(byteEndRoot, 0, byteEndRoot.Length); 

Not sure if this works or not.

Thanks a lot!

Answer

Andras Zoltan picture Andras Zoltan · May 25, 2011

Technically you should only ask one question per question, so I'm only going to answer the first one because this is just a quick visit to SO for me at the moment.

You need to call Flush before attempting to read from the Stream I think.

Edit Just bubbling up my second hunch from the comments below to justify the accepted answer here.

In addition to the call to Flush, if reading from the Stream is done using the Read method and its brethren, then the position in the stream must first be reset back to the start. Otherwise no bytes will be read.

ms.Position = 0; /*reset Position to start*/
StreamReader reader = new StreamReader(ms); 
string text = reader.ReadToEnd(); 
Console.WriteLine(text);