内存流是空的

编程入门 行业动态 更新时间:2024-10-24 10:28:00
本文介绍了内存流是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要生成来自不同来源(函数)一个巨大的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.

更多推荐

内存流是空的

本文发布于:2023-11-08 15:49:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   流是空

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!