# Wednesday, November 14, 2007

Everyone knows that an easy way to represent binary data in a normal ASCII, is to use Base64. Most people also know about the Convert.ToBase64String() and Convert.FromBase64String() methods in the .NET Framework. But how do you use this knowledge to convert any (serializable) object to/from a string, in as few lines of code as posssible?

Well, most (if not all) solutions I found on the net are making things a lot more complicated than they should be. So I decided to write my own and share it with you:

The 20-line Base64 Serializer/Deserializer

public static class Base64Serializer
{
    public static string Serialize(object obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            new BinaryFormatter().Serialize(memStream, obj);

            return Convert.ToBase64String(memStream.ToArray());
        }
    }

    public static T Deserialize<T>(string s)
    {
        using (MemoryStream memStream = new MemoryStream(Convert.FromBase64String(s)))
        {
            return (T) new BinaryFormatter().Deserialize(memStream);
        }
    }
}

kick it on DotNetKicks.com
Wednesday, November 14, 2007 4:59:25 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -

Comments are closed.