masterfy

 

对象和二进制流之间的转换

   public static class ConvertByte
    {
        /// <summary>
        /// 对象转换成二进制流
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToByte(object obj)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(stream, obj);
            byte[] bytes = stream.GetBuffer();
            stream.Close();
            return bytes;
        }

        /// <summary>
        /// 二进制流还原成对象
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static object ByteToObject(byte[] bytes)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Object reobj = bf.Deserialize(stream);
            stream.Close();
            return reobj;
        }
    }

posted on 2010-02-03 11:49  masterfy  阅读(1148)  评论(0编辑  收藏  举报

导航