首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XmlWriter OutOfMemoryException

XmlWriter OutOfMemoryException
EN

Stack Overflow用户
提问于 2012-12-12 12:25:42
回答 1查看 2.4K关注 0票数 0

当我将非常大的字符串数据(100 Mb)保存到Xml时,内存异常非常奇怪。有人对发生什么事有什么想法吗?我只使用2.0框架。

代码语言:javascript
复制
Exception Stack:

System.OutOfMemoryException was unhandled
Message=Exception of type 'System.OutOfMemoryException' was thrown.
Source=mscorlib
StackTrace:

at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(Char value)
at System.Xml.XmlTextWriter.InternalWriteEndElement(Boolean longFormat)
at System.Xml.XmlTextWriter.WriteEndElement()
at System.Xml.XmlWriter.WriteElementString(String localName, String ns, String 

SampleCode:

代码语言:javascript
复制
StreamWriter streamWriter = new StreamWriter( stream );
XmlTextWriter textWriter = new XmlTextWriter(streamWriter);
XmlWriter writer = textWriter;
writer.WriteStartDocument( true );
EN

回答 1

Stack Overflow用户

发布于 2012-12-12 12:37:45

虽然您的代码没有显示这一点,但您可能不会使用“使用”正确地打开和关闭XMLWriter流。如果您真的想写入内存,请传入一个StringBuilder。试试这个:-

代码语言:javascript
复制
using System;
using System.Text;
using System.Xml;
public class Test {
    static void Main()
    { 
        XmlWriterSettings settings = new XmlWriterSettings();
        StringBuilder builder = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(builder, settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("root");
            writer.WriteStartElement("element");
            writer.WriteString("content");
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
        }
        Console.WriteLine(builder);
}

}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13839742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档