Convert Object To Byte Array and Byte Array to Object in C#

This code snippet article is giving code examples to Convert object to byte array and Convert byte array to object in C#

You can convert object into byte array and byte array into object easily by using serialization in C#.

Note: for custom classes add [Serializable] attribute to enable serialization

Convert object to byte array

  private byte[] ObjectToByteArray(Object obj)
    {
      if (obj == null)
      return null;
      BinaryFormatter bf = new BinaryFormatter();
      MemoryStream ms = new MemoryStream();
      bf.Serialize(ms, obj);
      return ms.ToArray();
    }

Convert byte array to object

   private Object ByteArrayToObject(byte[] arrBytes)
     {
       MemoryStream memStream = new MemoryStream();
       BinaryFormatter binForm = new BinaryFormatter();
       memStream.Write(arrBytes, 0, arrBytes.Length);
       memStream.Seek(0, SeekOrigin.Begin);
       Object obj = (Object) binForm.Deserialize(memStream);
       return obj;
     }

Advertisement