Newbie
Newbie

Reputation: 1111

convert a class to byte array + C#

How can I convert a Class to byte array in C#. This is a managed one so the following code is failing

int objsize = System.Runtime.InteropServices.Marshal.SizeOf(objTimeSeries3D);
byte[] arr = new byte[objsize];
IntPtr buff = System.Runtime.InteropServices.Marshal.AllocHGlobal(objsize);
System.Runtime.InteropServices.Marshal.StructureToPtr(objTimeSeries3D, buff, true);
System.Runtime.InteropServices.Marshal.Copy(buff, arr, 0, objsize);
System.Runtime.InteropServices.Marshal.FreeHGlobal(buff);

Thanks

Upvotes: 5

Views: 23664

Answers (1)

Igal Tabachnik
Igal Tabachnik

Reputation: 31548

You can use BinaryFormatter. Note that your class must be [Serializable] for this to work.

private byte[] ToByteArray(object source)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream())
    {
        formatter.Serialize(stream, source);                
        return stream.ToArray();
    }
}

Upvotes: 16

Related Questions