Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7188619
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T19:07:25+00:00 2026-05-28T19:07:25+00:00

I am using the following code to get an xml string. public static string

  • 0

I am using the following code to get an xml string.

public static string ToXMLString(object obj, string nodeName)
{
    XmlSerializer xmlSerializer = default(XmlSerializer);
    string xml = string.Empty;
    StreamReader r = default(StreamReader);
    try
    {
        if (obj != null)
        {
            using (MemoryStream m = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(m, new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true }))
                {
                    // Don't include XML namespace
                    XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
                    xmlnsEmpty.Add("", "");
                    if (xmlSerializer == null)
                        xmlSerializer = new XmlSerializer(obj.GetType(), new XmlRootAttribute(nodeName));
                    xmlSerializer.Serialize(writer, obj, xmlnsEmpty);

                    m.Flush();
                    m.Position = 0;

                    r = new StreamReader(m);
                    xml = r.ReadToEnd();
                    xmlSerializer = null;
                }
            }
        }

        return xml;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }
    finally
    {
        r.Close();
        r.Dispose();
    }
    //XmlSerializer xmlSerializer;

}

I have a loop that runs using the method and after some time i get an out of memory exception as below:

What might the cause of the exception? Is using statement really disposing streams? Or what other alternative can i use?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T19:07:26+00:00Added an answer on May 28, 2026 at 7:07 pm

    I would expect the issue here is assembly saturation. XmlSerializer works by generating an assembly on the fly; if you use the XmlSerializer(Type) constructor, it caches it and looks it up; but for any other constructor it doesn’t. And assemblies can’t (usually) by unloaded. So you just get more and more and more assemblies eating your memory. You will need to cache the serializer if you are running this in a loop:

    using System;
    using System.Collections;
    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    
    public static class Program
    {
        static void Main()
        {
            // the loop here is from your comment
            for (int i = 0; i < 10000000; i++) { ToXMLString("test", string.Format("test")); Console.WriteLine(i); }
        }
    
        // why is this Hashtable? due to the threading semantics!
        private static readonly Hashtable serializerCache = new Hashtable();
    
        public static string ToXMLString(object obj, string nodeName)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            Type type = obj.GetType();
            var cacheKey = new { Type = type, Name = nodeName };
            XmlSerializer xmlSerializer = (XmlSerializer)serializerCache[cacheKey];
            if (xmlSerializer == null)
            {
                lock (serializerCache)
                { // double-checked
                    xmlSerializer = (XmlSerializer)serializerCache[cacheKey];
                    if (xmlSerializer == null)
                    {
                        xmlSerializer = new XmlSerializer(type, new XmlRootAttribute(nodeName));
                        serializerCache.Add(cacheKey, xmlSerializer);
                    }
                }
            }
            try
            {
    
                StringWriter sw = new StringWriter();
                using (XmlWriter writer = XmlWriter.Create(sw,
                    new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true }))
                {
                    // Don't include XML namespace
                    XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
                    xmlnsEmpty.Add("", "");
                    xmlSerializer.Serialize(writer, obj, xmlnsEmpty);
                }
                return sw.ToString();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                throw;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using following code to get List from xml file - public static
I am serializing objects to XML with the following code: public static string SerializeToString<T>(T
Using the following code I get a nice formatted string: Request.QueryString.ToString Gives me something
I am using this method to serialize my object: public static string XmlSerialize(object o)
I have the following code files: public interface IMod { string Name { get;
I'm using the following code to get the members of a group on my
I am using the following code to get an alphabetic number of a first
I'm using the following code to get an array with all sub directories from
I'm currently using the following PHP code: // Get all subordinates $subords = array();
I am using following PHP code for trigger creation but always get error, please

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.