C#串行化类,用于读写文件

串行化类,这种方式有局限,了解即可。
主要问题有二:
1、文件没有可读性,想手动改,没有相应工具不可能;
2、类的结构一旦发生变化,读已有的数据就会报错。
以后会推荐一个较好用的文件串行化。

范例是WinForm的

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace Serializable
{
    public partial class Form1 : Form
    {
        private Person person;
        private string filePath;
        private string fileDirectory;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            filePath = Path.Combine(Environment.CurrentDirectory, "Config\\Person.dat");
            fileDirectory = Path.Combine(Environment.CurrentDirectory, "Config");
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            if (!File.Exists(filePath))
            {
                return;
            }
            using (Stream stream = File.OpenRead(filePath))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                person = formatter.Deserialize(stream) as Person;
            }
            this.tbName.Text = person.Name;
            this.nudAge.Value = person.Age;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string name = this.tbName.Text;
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("姓名不能为空");
                return;
            }
            int age = Convert.ToInt32(this.nudAge.Value);
            if (age<=0 || age>200)
            {
                MessageBox.Show("年龄的值不对");
                return;
            }
            if (person == null)
            {
                person = new Person();
            }
            person.Name = name;
            person.Age = age;
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            using (Stream stream = File.Create(filePath))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, person);
            }
        }
    }
    [Serializable]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C#气氛组队员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值