Tuesday, 14 October 2008

Serialising, streams and strings

A common operation is to serialise and object to a string. I'm still finding better and better ways of doing this. My current favourite makes use of .Net 3.0's DataContract. It uses a UTF8Encoding and a MemoryStream as this ensures that the output XML is UTF8.

Enjoy!

using (MemoryStream stream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(SomeClass));
serializer.WriteObject(stream, instanceOfSomeClass);

// Serialisation defaults to UTF8Encoding when used with a stream.
// See Simple Serialization at http://msdn.microsoft.com/en-us/library/ms731073.aspx
string data = Encoding.UTF8.GetString(stream.ToArray());

// Do something useful with the data.
}

No comments: