内存流是空的 [英] Memory stream is empty

查看:167
本文介绍了内存流是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成来自不同来源(函数)一个巨大的XML文件。我决定使用的XmlTextWriter ,因为它使用比内存少的XmlDocument

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

首先,启动一个的XmlWriter 与底层的MemoryStream

First, initiate an XmlWriter with underlying MemoryStream

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



然后,我通过了的XmlWriter (注意XML作家保持打开,直到最后一刻)传递给函数生成XML文件的开头:

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?

另外,我对如何从不同的来源(函数)一个巨大的XML文件,一个一般性的问题。我现在要做的就是保持的XmlWriter 打开(我假设底层的内存流应打开为好),以每个功能和书写。在第一个功能,我不写根元素的结束。最后一个功能之后,我手动添加根元素的结尾:

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.

非常感谢!

推荐答案

从技术上讲,你应该只问每个问题一个问题,所以我只打算回答第一个,因为这仅仅是一个快速访问,所以对我的时刻。

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.

您需要调用的Flush 前试图从Stream我觉得阅读。

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

修改
刚刚从下面的评论冒泡我的第二个预感到这里证明接受的答案。

在除了调用刷新,如果从流中读取使用方法及其弟兄们,那么完成流中的位置,必须首先复位回到开始。否则,任何字节将被读取。

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.

这篇关于内存流是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆