C#读取txt文件并将数据存储在格式化数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9777206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# read txt file and store the data in formatted array
提问by Csharp_learner
I have a text file which contains following
我有一个包含以下内容的文本文件
Name address phone salary
Hyman Boston 923-433-666 10000
all the fields are delimited by the spaces.
所有字段都由空格分隔。
I am trying to write a C# program, this program should read a this text file and then store it in the formatted array.
我正在尝试编写一个 C# 程序,该程序应该读取此文本文件,然后将其存储在格式化的数组中。
My Array is as follows:
我的数组如下:
address
salary
When ever I am trying to look in google I get is how to read and write a text file in C#.
当我尝试在 google 中查看时,我得到的是如何在 C# 中读取和编写文本文件。
Thank you very much for your time.
非常感谢您的宝贵时间。
采纳答案by Welton v3.59
You can use File.ReadAllLines method to load the file into an array. You can then use a for loop to loop through the lines, and the string type's Split method to separate each line into another array, and store the values in your formatted array.
您可以使用 File.ReadAllLines 方法将文件加载到数组中。然后,您可以使用 for 循环遍历行,并使用字符串类型的 Split 方法将每一行分隔到另一个数组中,并将值存储在格式化的数组中。
Something like:
就像是:
static void Main(string[] args)
{
var lines = File.ReadAllLines("filename.txt");
for (int i = 0; i < lines.Length; i++)
{
var fields = lines[i].Split(' ');
}
}
回答by Tigran
Do not reinvent the wheel. Can use for example fast csv readerwhere you can specify a delimeteryou need.
不要重新发明轮子。可以使用例如快速 csv 阅读器,您可以在其中指定delimeter您需要的。
There are plenty others on internet like that, just search and pick that one which fits your needs.
互联网上还有很多其他类似的东西,只需搜索并选择适合您需求的那个。
回答by dustyhoppe
This answer assumes you don't know how much whitespace is between each string in a given line.
这个答案假设您不知道给定行中每个字符串之间有多少空格。
// 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));
}
}
}

