码迷,mamicode.com
首页 > 其他好文 > 详细

序列化和反序列化代码

时间:2017-07-03 23:49:13      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:style   public   bsp   get   反序列化   mode   new   static   file   

1.UserInfo对象类

[Serializable]
public class UserInfo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

2.Xml方式序列化和反序列化

public class XmlSerialization
{
    public static void XmlSerialize(UserInfo user)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UserInfo));
        StreamWriter sw = new StreamWriter("UserInfo.xml");
        serializer.Serialize(sw, user);
        sw.Close();
    }

    public static UserInfo XmlDeserialize()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UserInfo));
        FileStream fs = new FileStream("UserInfo.xml", FileMode.Open);
        UserInfo user = serializer.Deserialize(fs) as UserInfo;
        fs.Close();
        return user;
    }
}

3.Binary方式序列化和反序列化

public class RuntimeSerialization
{
    public static void BinarySerialize(UserInfo user)
    {
        FileStream fs = new FileStream(@"SerializeFile\UserInfo.bin", FileMode.Append);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(fs, user);
        fs.Close();
    }

    public static UserInfo BinaryDeserialize()
    {
        FileStream fs = new FileStream(@"SerializeFile\UserInfo.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        BinaryFormatter formatter = new BinaryFormatter();
        UserInfo user = formatter.Deserialize(fs) as UserInfo;
        fs.Close();
        return user;
    }
}

 

序列化和反序列化代码

标签:style   public   bsp   get   反序列化   mode   new   static   file   

原文地址:http://www.cnblogs.com/DaphneOdera/p/7113334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!