"Root element not found" - when reading a memory stream

I have a class that I am storing 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 at str and found that it is empty, but the collection has an object.

Any ideas on why this is happening?

+3
source share
1 answer

Yes - you save in the memory stream, leaving it at the end. You need to "rewind" it with:

ms.Position = 0;

before creation StreamReader:

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

However, you need to rewind it again before loading in XmlDocument, unless you delete these last two lines, which I suspect were for debugging only. For a good measure, also close the memory stream when we are 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);
}
+7

Source: https://habr.com/ru/post/1723915/


All Articles