When trying to read from a MemoryStream (which was written to by an XmlWriter),
it throws an ObjectDisposedException ("Cannot access a closed Stream.")
.
I stumbled upon the fact that closing the XmlWriter in the middle of the 'using' statement allows to code to return without throwing. Something is fishy here.
public static string SerializeToString(T obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var stream = new MemoryStream())
using (var writer = XmlWriter.Create(stream))
{
serializer.Serialize(writer, obj);
writer.Flush();
// Swapping the flush for close fixes the ObjectDisposedException
//writer.Close();
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
This happens for both Silverlight and .NET 4.5.
After reading around I could read a string from the memory stream directly as per Jon's answer here return Encoding.UTF8.GetString(stream.GetBuffer(), 0, stream.Length);
But first I'd like to understand what is happening to cause the exception in the example code.