Convert Object to Base64String

We can encode string as Base64String or decode Base64String to string using the below methods

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
But, if we want to encode an object to base64 it will not allow. For that we need to serialize the object as string first. It can be done by using either Newtonsoft.Json or BinaryFormatter class available in System.Runtime.Serialization.Formatters.Binary. Following are the code blocks for converting object to base64 and vice versa

Using Newtonsoft.Json

Encode

public static string Base64EncodeObject(object obj)
{
   var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
   return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static T Base64DecodeObject(string base64String)
{
  var base64EncodedBytes = System.Convert.FromBase64String(base64String);
  return JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(base64EncodedBytes));
}

Using BinaryFormatter Class

Encode

public static string Base64EncodeObject(object obj)
{
  using (MemoryStream ms = new MemoryStream())
  {
	  new BinaryFormatter().Serialize(ms, obj);
	  return Convert.ToBase64String(ms.ToArray());
  }
}

Decode

public static T Base64DecodeObject(string base64String)
{
  byte[] bytes = Convert.FromBase64String(base64String);
  using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
  {
	  ms.Write(bytes, 0, bytes.Length);
	  ms.Position = 0;
	  return (T)new BinaryFormatter().Deserialize(ms);
  }
}
Note: The class should be decorated with [Serializable] if it is a user defined class

Personally I prefer using Newtonsoft.Json as the generated Base64 string length is smaller than generated with BinaryFormatter class.
Happy Coding!😊

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment