如何使用 C# 解析文本文件?
问题描述:
我想制作一个 Windows 窗体应用程序,它将读取文本文件并将文本文件的字段放入文本框中.
I'd like to make a Windows Forms application that will read in a text file and put the fields of the text file into textboxes.
文本文件格式示例:
Name;Surname;Birthday;Address
Name;Surname;Birthday;Address
Winforms
Name: textboxname
Surname: textboxsurname
Birthday: textboxbirth
Address: textboxaddress
我还希望这个 Winforms 应用程序有一个 Next
和 Back
按钮,以便它可以循环浏览记录.
I also want this Winforms application to have a Next
and Back
button so it can cycle through the records.
我不知道如何在 C# 中执行此操作.我从哪里开始?
I don't know how to do this in C#. Where do I start?
答
在一个简单的形式中,你逐行读取文件,在 ;
上拆分每一行并使用值:
In a simple form, you read the file line by line, split each line on ;
and use the values:
// open the file in a way so that we can read it line by line
using (Stream fileStream = File.Open("path-to-file", FileMode.Open))
using (StreamReader reader = new StreamReader(fileStream))
{
string line = null;
do
{
// get the next line from the file
line = reader.ReadLine();
if (line == null)
{
// there are no more lines; break out of the loop
break;
}
// split the line on each semicolon character
string[] parts = line.Split(';');
// now the array contains values as such:
// "Name" in parts[0]
// "Surname" in parts[1]
// "Birthday" in parts[2]
// "Address" in parts[3]
} while (true);
}
此外,请查看 CSVReader,这是一个有助于处理此类文件的库.
Also, check out CSVReader which is library facilitating the handling of files like these.