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; }
    }
}

三种方法的文件存储内容

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

第二种:

第三种:

原文地址:https://www.cnblogs.com/chenyingzuo/p/15407212.html