我有一个文本文件,其中包含以下内容
Name address phone salary
Jack Boston 923-433-666 10000
所有字段都以空格分隔。
我正在尝试编写一个C#程序,该程序应该读取此文本文件,然后将其存储在格式化数组中。
我的数组如下:
address
salary
每当我尝试在谷歌上查找时,我得到的结果都是关于如何在C#中读写文本文件的内容。非常感谢您的时间。
我有一个文本文件,其中包含以下内容
Name address phone salary
Jack Boston 923-433-666 10000
所有字段都以空格分隔。
我正在尝试编写一个C#程序,该程序应该读取此文本文件,然后将其存储在格式化数组中。
我的数组如下:
address
salary
static void Main(string[] args)
{
var lines = File.ReadAllLines("filename.txt");
for (int i = 0; i < lines.Length; i++)
{
var fields = lines[i].Split(' ');
}
}
此答案假设您不知道每行中每个字符串之间有多少空格。
// Method to split a line into a string array separated by whitespace
private string[] Splitter(string input)
{
return Regex.Split(intput, @"\W+");
}
// Another code snippet to read the file and break the lines into arrays
// of strings and store the arrays in a list.
List<String[]> arrayList = new List<String[]>();
using (FileStream fStream = File.OpenRead(@"C:\SomeDirectory\SomeFile.txt"))
{
using(TextReader reader = new StreamReader(fStream))
{
string line = "";
while(!String.IsNullOrEmpty(line = reader.ReadLine()))
{
arrayList.Add(Splitter(line));
}
}
}