• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

永远有李

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

序列化

1、BinaryFormatter二进制序列化对象实例到文件

View Code
            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, obj);
            }
            catch (SerializationException e)
            {
                throw;
            }
            finally
            {
                fs.Close();
            }
View Code
        public static object Deserialize()
        {
            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                return formatter.Deserialize(fs);
            }
            catch (SerializationException e)
            {
                throw;
            }
            finally
            {
                fs.Close();
            }

        }

 2、BinaryFormatter二级制序列化对象

View Code
                IFormatter formatter = new BinaryFormatter();
                using (MemoryStream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, obj);
                    long count = stream.Length;
                    byte[] buff = stream.ToArray();
                    obj = Convert.ToBase64String(buff);
                }
View Code
IFormatter fter = new BinaryFormatter();
byte[] buff = Convert.FromBase64String(serializedObject);
using (Stream stream = new MemoryStream(buff))
{
    obj = fter.Deserialize(stream);
}

3、BinaryFormatter深拷贝

View Code
       public static T CloneOf<T>(T serializableObject)
        {
            object objCopy = null;

            MemoryStream stream = new MemoryStream();
            BinaryFormatter binFormatter = new BinaryFormatter();
            binFormatter.Serialize(stream, serializableObject);
            stream.Position = 0;
            objCopy = (T)binFormatter.Deserialize(stream);
            stream.Close();
            return (T)objCopy;
        }

 

 

posted on 2012-12-31 14:17  永远有李  阅读(97)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3