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?
I would expect the issue here is assembly saturation.
XmlSerializerworks by generating an assembly on the fly; if you use theXmlSerializer(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: