在.NET Framework中,有几种序列化方式可供选择,包括二进制序列化、XML序列化和JSON序列化。以下是.NET Framework中常用的序列化类:
BinaryFormatter
:将对象序列化为二进制格式。
XmlSerializer
:将对象序列化为XML格式。
DataContractSerializer
:将对象序列化为XML格式,并支持对数据进行版本控制。
JsonSerializer
:将对象序列化为JSON格式。
序列化一般需要两个步骤:
不使用序列化存
private void button4_Click(object sender, EventArgs e) {
//封装数据(数据一条一条的存储,这不属于面向对象编程的思想)
Student student = new Student() {
Name = this.name.Text.Trim(),
Sex = this.sex.Text.Trim(),
Age = this.age.Text.Trim(),
Brith = Convert.ToDateTime(this.dtpBirth.Text)
};
//执行本地存储
FileStream fs = new FileStream(@"D:\WinForms\文件操作(序列化)\学生信息.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(student.Name);
sw.WriteLine(student.Age);
sw.WriteLine(student.Sex);
sw.WriteLine(student.Brith);
sw.Close();
fs.Close();
MessageBox.Show("存储学生信息成功");
}
不使用序列化取
private void button3_Click(object sender, EventArgs e) {
FileStream fs = new FileStream(@"D:\WinForms\文件操作(序列化)\学生信息.txt", FileMode.OpenOrCreate);
StreamReader sr = new StreamReader(fs);
//一行一行读
Student student = new Student() {
Name = sr.ReadLine(),
Age = sr.ReadLine(),
Sex = sr.ReadLine(),
Brith = Convert.ToDateTime(sr.ReadLine())
};
sr.Close();
fs.Close();
//显示
MessageBox.Show($"{student.Name}:{student.Age}:{student.Sex}:{student.Brith}");
}
使用序列化存
private void button1_Click(object sender, EventArgs e) {
Student student = new Student() {
Name = this.name.Text.Trim(),
Sex = this.sex.Text.Trim(),
Age = this.age.Text.Trim(),
Brith = Convert.ToDateTime(this.dtpBirth.Text)
};
FileStream fs = new FileStream(@"D:\WinForms\文件操作(序列化)\学生信息2.txt", FileMode.OpenOrCreate);
//创建二进制格式化器
BinaryFormatter bf = new BinaryFormatter();
//调用序列化方法
bf.Serialize(fs, student);
//关闭流
fs.Close();
MessageBox.Show("存储学生成功");
}
使用序列化取
private void button2_Click(object sender, EventArgs e) {
FileStream fs = new FileStream(@"D:\WinForms\文件操作(序列化)\学生信息2.txt", FileMode.OpenOrCreate);
//创建二进制格式化器
BinaryFormatter bf = new BinaryFormatter();
Student student = bf.Deserialize(fs) as Student;
//关闭流
MessageBox.Show($"{student.Name}:{student.Age}:{student.Sex}:{student.Brith}");
}