最近在学习怎么将类进行序列化,保存到文件中
要点
C#中要实现类的序列化,需要用到命名空间为:
using System.Runtime.Serialization.Formatters.Binary;
如果要将序列化的类保存到文件中,那么还需要加入另一个命名空间:
using System.IO;
布局界面
自定义Student类
//类 序列化 一定要加上这个关键字
[Serializable]
class Student
{
//姓名
public String Name { get; set; }
//学校
public String School { get; set; }
//年龄
public int Age { get; set; }
//地址
public String Address { get; set; }
public Student(String name,String school,int age,String address) {
this.Name = name;
this.School = school;
this.Age = age;
this.Address = address;
}
}
实现按钮事件
常量
//路径
String path = “D:/data/”;
//文件名
String filename = “my.data”;
//初始化数据
Student stu = new Student(“张三”, “清华大学”, 25, “北京”);
2.写入数据按钮事件
private void button1_Click(object sender, EventArgs e)
{
FileStream fs = null;
//如果文件不存在
if (!File.Exists(path + filename))
{
fs = new FileStream(path + filename, FileMode.Create);
}
else
{
fs = new FileStream(path + filename, FileMode.Open);
}
//开始序列化
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, stu);
//关闭文件流,释放资源
fs.Close();
}
3.读取数据按钮事件
private void button2_Click(object sender, EventArgs e)
{
if (File.Exists(path + filename))
{
//反序列化
FileStream fs = new FileStream(path + filename, FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
Student stu = bf.Deserialize(fs) as Student;
fs.Close();
textBox1.Text = “姓名:” + stu.Name + “年龄:” + stu.Age + “学校:” + stu.School + “地址:” + stu.Address;
}else{
MessageBox.Show(“文件不存在”);
}
}
展示结果
先点击写入数据按钮,然后点击读取数据按钮,那么数据就会显示在TextBox中啦
更多烟台IT培训相关资讯,请扫描下方二维码