C# Serialization

Xml Serialization and Binary Serialization to a Base64 string

Xml Serialization

Snippit: Take a serializable object and serialize it into an xml string, stored in a System.Text.StringBuilder

System.Xml.Serialization.XmlSerializer serializer = 
    new System.Xml.Serialization.XmlSerializer(typeof(ObjectToSerialize));
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(sb))
{
    serializer.Serialize(stringWriter,  myObject);
    stringWriter.Close();
}

Binary Serialization to Base64 string

Snippit: Take a serializable object and serialize it into a Base64 string

byte[] bResult;
System.Runtime.Serialization.IFormatter formatter =
    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (System.IO.MemoryStream s = new System.IO.MemoryStream())
{
    formatter.Serialize(s, myObject);
    bResult = s.ToArray();
    s.Close();
}
string s = Convert.ToBase64String(bResult);

Snippit: Deserialize

ObjectToSerialize myObject = null;
byte[] b = Convert.FromBase64String(str);
System.Runtime.Serialization.IFormatter formatter =
    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (System.IO.MemoryStream ms = System.IO.new MemoryStream(b))
{
    myObject = (ObjectToSerialize)formatter.Deserialize(ms);
    ms.Close();
}