[英]C# read txt file and store the data in formatted array
我有一个包含以下内容的文本文件
Name address phone salary
Jack Boston 923-433-666 10000
所有字段都由空格分隔。
我正在尝试编写一个C#程序,该程序应该读取这个文本文件,然后将其存储在格式化的数组中。
我的数组如下:
address
salary
当我试图在google中查看时,我得到的是如何在C#中读写文本文件。
非常感谢您的宝贵时间。
您可以使用File.ReadAllLines方法将文件加载到数组中。 然后,您可以使用for循环遍历行,并使用字符串类型的Split方法将每行分隔为另一个数组,并将值存储在格式化的数组中。
就像是:
static void Main(string[] args)
{
var lines = File.ReadAllLines("filename.txt");
for (int i = 0; i < lines.Length; i++)
{
var fields = lines[i].Split(' ');
}
}
不要重新发明轮子。 可以使用例如快速csv阅读器 ,您可以在其中指定所需的delimeter
。
互联网上有很多其他类似的东西,只需搜索并选择一个符合您需求的产品。
这个答案假设您不知道给定行中每个字符串之间有多少空格。
// 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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.