c# 常用的几种方法序列化和反序列化

c# 允许把数据序列化成某种格式,存储在文件里,然后可以在其他机器上,读取文件内容,再反序列化成数据

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WindowsFormsApp75
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            var stu1 = new Student("Zhangsan", 20, "Xian");

            // Binary Format
            // MS announced dangerous and is not recommended
            var binaryForamtter = new BinaryFormatter();
            using (var fs1 = new FileStream("binary.txt", FileMode.Create))
            {
                binaryForamtter.Serialize(fs1, stu1);
            }
            using (var fs2 = new FileStream("binary.txt", FileMode.Open))
            {
                var result = binaryForamtter.Deserialize(fs2);
            }

            // Xml
            // MS announced it's safe
            var serializer = new XmlSerializer(typeof(Student));
            using (var fs1 = new FileStream("xml.txt", FileMode.Create))
            {
                serializer.Serialize(fs1, stu1);
            }
            using (var fs2 = new FileStream("xml.txt", FileMode.Open))
            {
                var result = serializer.Deserialize(fs2);
            }

            // DataContractSerializer
            // MS announced it's safe
            var serializer2 = new DataContractSerializer(typeof(Student));
            using (var fs1 = new FileStream("data.txt", FileMode.Create))
            {
                serializer2.WriteObject(fs1, stu1);
            }
            using (var fs2 = new FileStream("data.txt", FileMode.Open))
            {
                var result = serializer2.ReadObject(fs2);
            }
        }
    }

    [Serializable]
    public class Student
    {
        public Student()
        {

        }
        public Student(string name, int age, string address)
        {
            this.Name = name;
            this.Age = age;
            this.Address = address;
        }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
}
复制代码

 

三种方法的文件存储内容

第一种,打不开,存储的是字节流,不是字符串

第二种:

 

 

第三种:

 

posted @   内心澎湃的水晶侠  阅读(770)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示