C# 物件轉換為byte[] ,byte[]還原物件
///<summary>
///將一個object物件序列化,返回一個byte[]
///</summary>
///<paramname="obj">能序列化的物件</param>
///<returns></returns>
public static byte[] ObjectToBytes(object obj)
{
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();
}
}
///<summary>
///將一個序列化後的byte[]陣列還原
///</summary>
///<paramname="Bytes"></param>
///<returns></returns>
public static object BytesToObject(byte[] Bytes)
{
using (MemoryStream ms = new MemoryStream(Bytes))
{
IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms);
}
}