sblandin
sblandin

Reputation: 964

Dataset XML serialization to memory stream

I have a strongly typed DataSet and a corresponding class generated with xsd.exe.

I wanted to pass DataSet content to the matching class with XML serialization/deserialization.

If I use something like:

MyStronglyTypedDataSet ds = new MyStronglyTypedDataSet();
//... fill the dataset...
ds.WriteXml(@"C:\Temp\somedata.xml");

FileStream fs = new FileStream(@"C:\Temp\somedata.xml", FileMode.Open);
XmlSerializer serial = new XmlSerializer(typeof(MyDataSetMatchingClass));
MyDataSetMatchingClass myObj = (MyDataSetMatchingClass)serial.Deserialize(fs);

Everything works fine, but I don't want to use a temporary file so I tried:

MyStronglyTypedDataSet ds = new MyStronglyTypedDataSet();
//... fill the dataset...
MemoryStream dump = new MemoryStream();
ds.WriteXml(dump);

XmlSerializer serial = new XmlSerializer(typeof(MyDataSetMatchingClass));
MyDataSetMatchingClass myObj = (MyDataSetMatchingClass)serial.Deserialize(dump);

But the deserializer complains that root XML node is missing. Anyone knows a way to tell the XmlWriter to append the root node, or the deserializer to ignore missing root node or any other solution?

Upvotes: 1

Views: 1532

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

You didn't rewind the stream. This is a very common problem (see How many ways can you mess up IO? - look for "Gotchas when buffering data in memory"). Set:

dump.Position = 0;

between the write (serialize) and the read (deserialize).

Upvotes: 2

Related Questions