Use the BinaryFormatter
:
byte[] ObjectToByteArray(object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Note that obj
and any properties/fields within obj
(and so-on for all of their properties/fields) will all need to be tagged with the Serializable
attribute to successfully be serialized with this.