The memory stream is empty.

I need to create a huge XML file from various sources (functions). I decided to use XmlTextWriteras it uses less memory than XmlDocument.

First run XmlWriterwith basicMemoryStream

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

Then I pass XmlWriter(the xml-writer note remains open until the very end) to the 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 the main memory stream is empty (by converting the byte array into a string and an output string). Any ideas why?

, , XML (). XmlWriter ( , ) . . :

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

, .

!

+3
3

, , , SO.

, Flush, Stream.

Edit , .

Flush, Read , . .

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

, Flush() xml, streazm.

+1

, Flush XmlTextWriter.

+1

All Articles