c# - 如何在 C# 中解析和使用文本文件中的行
问题描述
所以我正在尝试创建一个 Windows 窗体程序。该程序应该使用菜单条打开一些包含学生姓名、班级和一系列成绩的文本行的各种文本文件。然后程序将姓名/班级添加到表格上的标签中,并将成绩添加到数组中,然后用于计算最终分数。我设法让程序让我打开文本文件。然后我能够将所有信息放入一个富文本框中。
但是,现在我正在尝试解析这些行并利用它们。我正在尝试将行划分为变量并将它们拆分到有逗号的地方。
我尝试使用 string[] textSplit = OpenFile.Split(","); 但我得到一个错误。
如何拆分文本片段,然后如何实际与每一行交互?接下来我应该做什么?我迷路了。
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"",
Title = "Browse Text Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
Filter = "txt files (*.txt)|*.txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
}
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
string[] textSplit = OpenFile.Split(",");
}
解决方案
以下逻辑可能有助于您实际与每一行进行交互:
//read all lines of the file into an array
//foreach string in the array
//split the line on comma and store in an array X
然后您可以使用索引访问该行的特定单词