在将非常大的字符串数据(100 Mb)保存到Xml时,我得到一个非常奇怪的内存不足异常。我不确定。有没有人对发生的事情有任何想法?我只限于使用2.0框架。
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:
StreamWriter streamWriter = new StreamWriter( stream );
XmlTextWriter textWriter = new XmlTextWriter(streamWriter);
XmlWriter writer = textWriter;
writer.WriteStartDocument( true );
答案 0 :(得分:1)
虽然你的代码没有,但你可能不会这样;显示这一点,正确地打开和关闭XMLWriter流,使用“using”。如果你真的想写入内存,请传入一个StringBuilder。试试这个: -
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);
}
}