首页 > 代码库 > 序列化和反序列化代码
序列化和反序列化代码
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; } }
序列化和反序列化代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。