C# study notes-serialization and deserialization file operations

In the program, the serialized save data (small) will have an encryption effect.

File serialization operation (for entity classes)

1. Add serialization mark [Serializable] to the entity class

    /// <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. Serialization operation

       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. Deserialization operation

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

Add the code of the object

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

Full Demo link: https://download.csdn.net/download/qq_39157152/14927570

Guess you like

Origin blog.csdn.net/qq_39157152/article/details/113094565