0

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 );
3
  • Do you have to write all 100MB at once - can you possibly do it in chunks? Commented Dec 12, 2012 at 12:34
  • @dash: using XmlWriter means it is written in chunks. Commented Dec 12, 2012 at 12:36
  • @HenkHolterman I wasn't very clear, but I meant the original string - rather than write out all 100MB of data from a string in memory, load a bit, write a bit, load a bit, write a bit... to a file on disk :-) Commented Dec 12, 2012 at 12:51

1 Answer 1

1

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

}

Sign up to request clarification or add additional context in comments.

1 Comment

I was facing same problem, me just added writer.Flush(); and it started working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.