开发者

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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜