user1897659
user1897659

Reputation: 41

XmlWriter OutOfMemoryException

I'm getting a very weird out of memory exception when saving very large string data(100 Mb) to Xml..I'm not sure. Does anyone have any ideas on what's happening? and I restricted to use only 2.0 framework.

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 );

Upvotes: 0

Views: 2670

Answers (1)

mashtheweb
mashtheweb

Reputation: 167

You may be not although your code doesn;t show this, opening and closing the XMLWriter stream correctly, with "using". If you really want to write into memory, pass in a StringBuilder. Try this: -

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);
}

}

Upvotes: 1

Related Questions