转载自   https://blog.csdn.net/scimence/article/details/52233656

 

object与byte[]互转

///

/// 工具类:对象与二进制流间的转换

///

class ByteConvertHelper

{

///

/// 将对象转换为byte数组

///

/// 被转换对象

/// 转换后byte数组

public static byte[] Object2Bytes(object obj)

{

byte[] buff;

using (MemoryStream ms = new MemoryStream())

{

IFormatter iFormatter = new BinaryFormatter();

iFormatter.Serialize(ms, obj);

buff = ms.GetBuffer();

}

return buff;

}

///

/// 将byte数组转换成对象

///

/// 被转换byte数组

/// 转换完成后的对象

public static object Bytes2Object(byte[] buff)

{

object obj;

using (MemoryStream ms = new MemoryStream(buff))

{

IFormatter iFormatter = new BinaryFormatter();

obj = iFormatter.Deserialize(ms);

}

return obj;

}

}

 

好文推荐

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。