C# 读取 .txt 文件,存储其数据并编辑文件

C# Read .txt file, store its data and edit the file

我正在尝试做一些非常简单的事情。我正在制作一个 Windows 表单应用程序,它本质上是一个简单的 'Student grade calculator'。我有表格工作,它可以读取文件并在文本框中显示其数据。但是,我需要将每一行的列存储在它们自己的字段中。

您可以在下面看到一个文件示例,它应该 read/edit/save。

这是我目前用来读取文件的内容:

      private void LoadFile()
    {
        string lineFromFile;

        fileContentTextBox.Clear();

        try
        {
            using (StreamReader reader = new StreamReader(fileName))
            {
                while (!reader.EndOfStream)
                {
                    lineFromFile = reader.ReadLine();

                    fileContentTextBox.AppendText(lineFromFile);

                    fileContentTextBox.AppendText(Environment.NewLine);
                }
            }

那么,我如何才能将其数据存储在以下字段中:

我知道你必须使用这样的东西,但我不确定在这种情况下如何使用它,因为我需要在许多单独的字段中存储文件的数据?

    lines[i].Split(',')

表单中的输出最终看起来像这样:

如果有更好的方法,比如将每一行变成一个字符串然后将其分开或其他方法,请告诉我。

我无法用代码描述,因为我在 phone,但我会这样做:

创建一个新的 class,如果你愿意,可以称之为学生。在学生内部,创建您需要的属性(例如标记、称重)。

在您的主程序中,创建一个新的学生列表。

在你的 while 循环中,你读这行的地方,创建一个新学生。然后,将该行拆分为您的字符串数组。按索引访问字符串数组,获取您的属性并将值分配给学生属性。

最后,将创建的学生添加到学生列表中。

更新一些代码

好的,让我们假设您正在为学生创建通讯录。

你会有 Student class:

public class Student
{
     public string Name {get;set;}
     public int Age {get;set;}
}

然后在你的主程序中,你想创建一个列表来存储你的学生:

var students = new List<Student>();

最后,您想读取文件,创建您的学生并将 him/her 添加到列表中:

while (!reader.EndOfStream)
{
     var student = new Student();
     ineFromFile = reader.ReadLine();
     var arrayOfProperties = ineFromFile.Split();
     student.Name = arrayOfProperties[0]; #Make sure you know the indices, or you will have to create a custom parser ;)
     student.Age = (int)arrayOfProperties[1]; #Remember to convert from string.
     students.Add(student); # add your student!
}