tags:

views:

80

answers:

1

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?

+4  A: 

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);
}
Jon Skeet
Jon you save the day again :) Thank You.
Nick