Wednesday, 11 February 2015

C# - Serialize and Deserialize using BinaryFormatter with Strings (WITHOUT Files)


This code snippet will allow you to Serialize and DeSerialize any serializable object to a standard string and back. No need for binary files!

Usage:
Code Snippet
  1. // Inits
  2. CustomClass instance = new CustomClass();
  3.  
  4. // Serialize
  5. string data = SerializeObject<CustomClass>(instance);
  6.  
  7. // DeSerialize
  8. CustomClass instance = DeSerializeObject<CustomClass>(data);
End of Code Snippet


Code Snippet
  1. // NOTE: The result of serializing an object with BinaryFormatter is an octet stream, not a string.
  2. //       If we encode the serialized object with Base64, we will get our string.
  3. public static string SerializeObject<T>(T toSerialize)
  4. {
  5.     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  6.  
  7.     if (!toSerialize.GetType().IsSerializable)
  8.     {
  9.         throw new Exception("Object cannot be serialized in it's current state.");
  10.     }
  11.  
  12.     using (MemoryStream ms = new MemoryStream())
  13.     {
  14.         new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(ms, toSerialize);
  15.         return Convert.ToBase64String(ms.ToArray());
  16.     }
  17. }
  18.  
  19. public static T DeSerializeObject<T>(string data)
  20. {
  21.     byte[] bytes = Convert.FromBase64String(data);
  22.  
  23.     using (MemoryStream ms = new MemoryStream(bytes))
  24.     {
  25.         return (T)new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Deserialize(ms);
  26.     }
  27. }
End of Code Snippet

No comments: