2012-12-12 59 views
0

當我將超大字符串數據(100 Mb)保存到Xml時,我收到了一個非常奇怪的內存不足異常。我不確定。有沒有人有什麼想法發生了什麼?我僅限於使用2.0框架。XmlWriter OutOfMemoryException

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

你必須一次全部寫入100MB - 你能可能做到這一點在大塊? – dash

+0

@dash:使用XmlWriter表示它是以塊寫入的。 –

+0

@HenkHolterman我不是很清楚,但我的意思是原始字符串 - 而不是從內存中的字符串中寫出所有100MB的數據,加載一點,寫一點,加載一點,寫一點......到磁盤上的文件:-) – dash

回答

1

您可能沒有,雖然你的代碼沒有按;噸證明這一點,打開和關閉正確XMLWriter的流,以 「用」。如果你真的想寫入內存,傳入一個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); 
} 

}

+0

我面臨同樣的問題,我只是添加了writer.Flush();它開始正常工作。 –