程序中,序列化保存数据(小),会有加密作用。
文件的序列化操作(针对实体类)
1.对实体类添加序列化标记[Serializable]
/// <summary>
/// 学生的实体类
/// </summary>
[Serializable]
public class StudentModel
{
public string StuName { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
2.添加System.Runtime.Serialization.Formatters.Binary,using System.IO;引用
3.序列化操作
private void btnSerialize_Click(object sender, EventArgs e)
{
//1、创建文件流
FileStream fs=new FileStream("Student.stu", FileMode.Create);
//2、创建二进制格式化对象
BinaryFormatter formatter = new BinaryFormatter();
//3、执行序列化的方法
formatter.Serialize(fs,studentList);
//4.关闭文件流
fs.Close();
}
4.反序列化操作
private void btnDeserialize_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + "\\student.stu";
if (!File.Exists(path))
{
MessageBox.Show("未添加数据文件,请添加数据", "提示");
return;
}
//1.创建文件流
FileStream fs = new FileStream(path, FileMode.Open);
//2.创建二进制格式化对象
BinaryFormatter formatter = new BinaryFormatter();
//3.执行反序列化方法
studentList = (List<StudentModel>)formatter.Deserialize(fs);
//4.关闭文件流
fs.Close();
//5.显示数据
dgvStudentList.DataSource = null;
dgvStudentList.DataSource = studentList;
}
添加对象的code
private void btnAdd_Click(object sender, EventArgs e)
{
#region 数据校验
//数据校验
if (txtName.Text.Trim().Length==0)
{
MessageBox.Show("请输入学生姓名", "提示");
return;
}
if (txtAge.Text.Trim().Length == 0)
{
MessageBox.Show("请输入学生年龄", "提示");
return;
}
if(!(cbbSex.Text.Trim()=="男"||cbbSex.Text.Trim() == "女"))
{
MessageBox.Show("输入的性别有误", "提示");
return;
}
#endregion
//封装学生对象
StudentModel student = new StudentModel
{
StuName = txtName.Text.Trim(),
Sex=cbbSex.Text.Trim(),
Age=Convert.ToInt32(txtAge.Text.Trim())
};
studentList.Insert(0,student);
dgvStudentList.DataSource = null;
dgvStudentList.DataSource = studentList;
}
完整Demo链接:https://download.csdn.net/download/qq_39157152/14927570