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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}
}
▲ 这里改成属性会比较好。

运行效果:

保存至对象

感谢支持!