C# 使用文本保存对象信息

可以对象的信息保存到文本中,一行一行的保存,然后读取的时候一行一行的读取。缺点:如果行数错乱了,那读出来也是错乱的。这里只是一种思路。

只做练习,很多异常情况没有处理。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace SaveClassInfoToFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        // 保存至文本
        private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(@"./student.info", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            Student stu = new Student() {
                name = this.txtName.Text.Trim(),
                age = int.Parse(this.txtAge.Text.Trim()),
                gender = this.txtGender.Text.Trim(),
                brithday = this.txtBrith.Text.Trim()
            };

          
            // 一行一行的写
            sw.WriteLine(stu.name);
            sw.WriteLine(stu.age);
            sw.WriteLine(stu.gender);
            sw.WriteLine(stu.brithday);

            sw.Close();
            fs.Close();


            //System.Diagnostics.Process.Start("notepad", "./student.info");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(@"./student.info", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            Student stu = new Student() {
                name = sr.ReadLine().Trim().ToString(),
                age = int.Parse(sr.ReadLine().Trim()),
                gender = sr.ReadLine().Trim().ToString(),
                brithday = sr.ReadLine().Trim().ToString()
            };

            sr.Close();
            fs.Close();
            // 一行一行的读
            this.txtAge.Text = stu.age.ToString();
            this.txtGender.Text = stu.gender;
            this.txtName.Text = stu.name;
            this.txtBrith.Text = stu.brithday;
        }
    }
}

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SaveClassInfoToFile
{
    class Student
    {
        public string name;
        public int age;
        public string gender;
        public string brithday;
    }
}

▲ 这里改成属性会比较好。

运行效果:

posted @ 2021-09-26 13:43  double64  阅读(257)  评论(0)    收藏  举报