C#.Net: Out of memory exception while creating XML string with XML Searlization

Hello,

I've a project in which I pass collection and it converts in XML string.
But when below method creates 50 to 60 MB files then it does create 2 or 3 files but after that it does day "Out of memory exception"

Note: the machine RAM is 4 GB

I am using below method:

public string ToXMLString(CollectionData data)
{
           
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stringWriter);
           
            writer.Formatting = Formatting.Indented;
           
            XmlSerializer serializer = new XmlSerializer(typeof(CollectionData));
           
            serializer.Serialize(writer, data);
            writer.Flush();
            string XmlizedString = stringWriter.ToString();
            stringWriter.Close();
            writer.Close();
            return XmlizedString;
}

Could you please look into it on urgent basis?

Best Regards,
Mohit Pandit
LVL 6
MohitPanditAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Try disposing of your objects:

public string ToXMLString(CollectionData data)
{
           
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            
            writer.Formatting = Formatting.Indented;
            
            XmlSerializer serializer = new XmlSerializer(typeof(CollectionData));
            
            serializer.Serialize(writer, data);
            writer.Flush();
            string XmlizedString = stringWriter.ToString();
            stringWriter.Close();
            stringWriter.Dispose();
            writer.Close();
            writer.Dispose();
            return XmlizedString;
}

Open in new window

0
Arthur_WoodCommented:
alternatively:

public string ToXMLString(CollectionData data)
{
           
            using (StringWriter stringWriter = new StringWriter()){
                  using (XmlTextWriter writer = new XmlTextWriter(stringWriter)){
           
                        writer.Formatting = Formatting.Indented;
           
                        XmlSerializer serializer = new XmlSerializer(typeof(CollectionData));
           
                        serializer.Serialize(writer, data);
                        writer.Flush();
                       string XmlizedString = stringWriter.ToString();
                       return XmlizedString;
             }
      }
}

AW
0
Naman GoelPrinciple Software engineerCommented:
Yes, Both XmlTextWriter is having File Handle and Stream Handle so you should dispose that so that it will cleanup unmanaged resources, The best way to do this is by using "using" block as suggested by  Arthur_Wood.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Arthur_WoodCommented:
like this:

public string ToXMLString(CollectionData data)
{
           
            using (StringWriter stringWriter = new StringWriter()){
                  using (XmlTextWriter writer = new XmlTextWriter(stringWriter)){
           
                        writer.Formatting = Formatting.Indented;
           
                        using (XmlSerializer serializer = new XmlSerializer(typeof(CollectionData))){

                             serializer.Serialize(writer, data);
                        }
                        writer.Flush();
                       string XmlizedString = stringWriter.ToString();
                       return XmlizedString;
             }
      }
}
0
käµfm³d 👽Commented:
The best way to do this is by using "using" block as suggested by  Arthur_Wood.
I wouldn't go so far as to say that it's necessarily the "best" method to do it, but it is recommended practice to do such. (There are rare occurrences where a using actually complicates debugging.)
0
MohitPanditAuthor Commented:
Hi AW,

I've used your code, but it is giving an error on below line:

using (XmlSerializer serializer = new XmlSerializer(typeof(CollectionData))){

The error is "System.Xml.Serialization.XmlSerializer: type used in using statement must be implicitly convertible to 'System.IDisposable'"

Could you please look into it?


Best Regards,
Mohit Pandit
0
Naman GoelPrinciple Software engineerCommented:
XmlSerializer is not a disposable object so it should not be in using block, you should try  solution proposed by Arthur_Wood .
0
MohitPanditAuthor Commented:
Ok, thanks. let me try
0
Arthur_WoodCommented:
public string ToXMLString(CollectionData data)
{
           
            using (StringWriter stringWriter = new StringWriter()){
                  using (XmlTextWriter writer = new XmlTextWriter(stringWriter)){
           
                        writer.Formatting = Formatting.Indented;
           
                        XmlSerializer serializer = new XmlSerializer(typeof(CollectionData))

                        serializer.Serialize(writer, data);
                        writer.Flush();
                       string XmlizedString = stringWriter.ToString();
                       return XmlizedString;
             }
      }
}
0
MohitPanditAuthor Commented:
Hi AW,

I've used but still it is giving same exception i.e. out of memory :-(...

do you have other thoughts?

Best Regards
0
Naman GoelPrinciple Software engineerCommented:
are you having any memory profiler, if so please use http://memprofiler.com/ and check which object is causing the problem.
0
Arthur_WoodCommented:
There would appear to be a memory leak somewhere.  It is probably not in the code that you have been working with.  That is why naman's suggestion should get you looking in the right place.

AW
0
käµfm³d 👽Commented:
How quickly are you calling this code? Disposal is not guaranteed to be instantaneous. If you had a tight enough loop running, it would still be possible to have disposed of objects in memory whilst you are attempting to create new objects.
0
jonnidipCommented:
This is a simplified version of the method I use to serialize objects.
Please give it a try:
using (MemoryStream ms = new MemoryStream())
{
    new XmlSerializer(typeof(CollectionData)).Serialize(ms, data);
    ms.Position = 0;

    using (StreamReader sr = new StreamReader(ms))
    {
        return sr.ReadToEnd();
    }
}

Open in new window


Regards.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MohitPanditAuthor Commented:
thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.