5

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

1
  • Why do you need to convert a class to a byte array? If we know the problem you are trying to solve, we may have a better way of doing things. Commented Apr 22, 2010 at 8:28

1 Answer 1

16

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.