Thomas Huber
Thomas Huber

Reputation: 1302

Deserializing XML File using XmlSerializer.Deserialize from MemoryStream not working

I'm having trouble deserializing my XML file from a MemoryStream. I have a generated MyXmlFile class and a MemoryStream containing an XML file which I want to deserialize into an object of type MyXmlFile.

public static class XmlSerializeObject
{
    public static T FromStream<T>(Stream s)
    {
        var serializer = new XmlSerializer(typeof(T));
        return (T) serializer.Deserialize(s);
    }
}

I have a MemoryStream ms which contains an xml file. If I try to deserialize that stream into an object of type MyXmlFile I get an exception "There is an error in XML document (0,0)"

MyXmlFile test = XmlSerializeObject.FromStream<MyXmlFile>(ms);

However I verified that my MemoryStream is correct. If I first write my stream into a file on my disc and than read that file again it works fine.

        FileStream outStream = File.OpenWrite("D:\\p.xml");
        outStream.Write(((MemoryStream)ms).ToArray(), 0, ((MemoryStream)ms).ToArray().Length);
        outStream.Flush();
        outStream.Close();
        MyXmlFile test= XmlSerializeObject.FromStream<MyXmlFile>(File.OpenRead("D:\\p.xml"));

I was not able to find a solution myself that is why I decided to post my question. Maybe someone had the same problem before and is able to help me out.

Thanks in advance. If anything is unclear please ask.

Upvotes: 3

Views: 3728

Answers (2)

TcKs
TcKs

Reputation: 26642

You must set position of MemoryStream to the 0.

((MemoryStream)ms).Position = 0;
MyXmlFile test = XmlSerializeObject.FromStream<MyXmlFile>(ms);

Upvotes: 1

AllenG
AllenG

Reputation: 8190

If you instantiated your memory stream prior to your call to deserialize (say, to load the XML into the memory stream in the first place) it may be that it's at the wrong index. Try

ms.Seek(0, SeekOrigin.Begin)

To go back to the beginning of the stream.

Upvotes: 7

Related Questions