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 @   double64  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示