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

1 comment:

Gabe Co Hadwin said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.