代码改变世界

C# 序列化

2008-05-14 08:19  zhangbaoyu  阅读(465)  评论(0编辑  收藏  举报

//序列化
        public string SoapOutput(object obj)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            formatter.Serialize(memoryStream, obj);

            byte[] aryByte = memoryStream.ToArray();

            string base64 = Convert.ToBase64String(aryByte, 0, aryByte.Length);
            memoryStream.Close();
            return base64;
        }

        //反序列化
        public object SoapInput(string base64)
        {

            byte[] aryByte = Convert.FromBase64String(base64);

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream(aryByte, 0, aryByte.Length);
            object obj = (Object)formatter.Deserialize(memoryStream);
            memoryStream.Close();
            return obj;
        }