Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Root element not found" - when reading memory stream

Tags:

c#

.net

xml

I have a class that i store in a list.

I serialize it ...

        XmlDocument xd = new XmlDocument();
        MemoryStream ms = new MemoryStream();
        XmlSerializer xm = new XmlSerializer(typeof(List<BugWrapper>));

        xm.Serialize(ms, _bugs);
        StreamReader sr = new StreamReader(ms);
        string str = sr.ReadToEnd();
        xd.Load(ms);

I looked into str and found it to be empty, the collection however has an object.

Any ideas into why this happens?

like image 902
Developer Avatar asked Sep 14 '26 23:09

Developer


1 Answers

Yes - you're saving to the memory stream, leaving it at the end. You need to "rewind" it with:

ms.Position = 0;

just before you create the StreamReader:

xm.Serialize(ms, _bugs);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string str = sr.ReadToEnd();

However, you then need to rewind it again before you load into the XmlDocument unless you remove those last two lines, which I suspect were just for debugging. Just for good measure, let's close the memory stream as well when we're done with it:

using (MemoryStream stream = new MemoryStream())
{
     XmlSerializer serializer = new XmlSerializer(typeof(List<BugWrapper>));
     seralizer.Serialize(stream, _bugs);
     stream.Position = 0;

     XmlDocument doc = new XmlDocument();
     doc.Load(stream);
}
like image 123
Jon Skeet Avatar answered Sep 16 '26 11:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!