Memory stream is empty

风格不统一 提交于 2019-12-01 05:15:23

问题


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!


回答1:


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); 



回答2:


Perhaps you need to call Flush() on the xml stream before checking the memory streazm.




回答3:


Make sure you call Flush on the XmlTextWriter before checking the memory stream.



来源:https://stackoverflow.com/questions/6130469/memory-stream-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!