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.Marsha开发者_开发知识库l.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
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();
}
}
精彩评论