C#学习笔记-序列化和反序列化文件操作

程序中,序列化保存数据(小),会有加密作用。

文件的序列化操作(针对实体类)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值