Xsd2Code序列化文件OutOfMemoryException

时间:2015-04-07 17:05:27

标签: c# .net

我使用 Xsd2Code 序列化我的对象以生成Xml文件。

它工作正常,只是当文件包含大量数据时,我得到OutOfMemoryException。这是我用来序列化对象的代码:

/// Serializes current EntityBase object into an XML document
/// </summary>
// <returns>string XML value</returns>
public virtual string Serialize() {
    System.IO.StreamReader streamReader = null;
    System.IO.MemoryStream memoryStream = null;

    try {
        memoryStream = new System.IO.MemoryStream();
        Serializer.Serialize(memoryStream, this);
        memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
        streamReader = new System.IO.StreamReader(memoryStream);
        return streamReader.ReadToEnd();
    }
    finally {
        if (streamReader != null) {
            streamReader.Dispose();
        }

        if (memoryStream != null) {
            memoryStream.Dispose();
        }
    }
}

我的请求是,如何扩展内存缓冲区,或者如何避免这种异常?

的问候。

1 个答案:

答案 0 :(得分:1)

您没有显示ToString()的完整OutOfMemoryException输出,因此很难确定这会有多大帮助,但有一种可能性就是直接写入StringWriter无需创建中间MemoryStream,如下所示:

    public virtual string Serialize()
    {
        return this.Serialize(Serializer);
    }

使用扩展方法:

public static class XmlSerializerExtensions
{
    class NullEncodingStringWriter : StringWriter
    {
        public override Encoding Encoding { get { return null; } } 
    }

    public static string Serialize<T>(this T obj, XmlSerializer serializer = null, bool indent = true)
    {
        if (serializer == null)
            serializer = new XmlSerializer(obj.GetType());
        // Precisely emulate the output of http://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/XmlSerializer.cs,2c706ead96e5c4fb
        // - Indent by 2 characters
        // - Suppress output of the "encoding" tag.
        using (var textWriter = new NullEncodingStringWriter())
        {
            using (var xmlWriter = new XmlTextWriter(textWriter))
            {
                if (indent)
                {
                    xmlWriter.Formatting = Formatting.Indented;
                    xmlWriter.Indentation = 2;
                }
                serializer.Serialize(xmlWriter, obj);
            }
            return textWriter.ToString();
        }
    }
}

您还可以考虑通过设置indent = false来消除格式和缩进以节省更多字符串内存。

这会稍微减少峰值内存占用,因为它完全消除了在结果字符串的同时在内存中有大MemoryStream的需要。但是,它不会极大地降低峰值内存需求,因为MemoryStream占用的内存将与最终XML string占用的内存成比例。

除此之外,我只能建议尝试stream directly to your database