我需要初始化一个二维数组,并将文件中的每一行作为第一列。如何获取文件中的行数?
你可以这样做:
System.IO.File.ReadAllLines("path").Length
正如Joe所指出的那样,我省略了所有标准错误处理,并且没有展示您将如何在其余代码中使用此相同的数组进行处理。
来自MSDN:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
为获取计数,您需要逐行打开读取文件:
var lines = File.ReadAllLines(filename);
var count = lines.Length;
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\t1.txt");
while((line = file.ReadLine()) != null)
{
counter++;
}
file.Close();
计数器将给出行数。您可以使用循环将行插入到数组中。
你最好打开文件,将每一行读入一个列表中,然后创建你的二维数组,这样会更加实用。
List<string> lines = new List<string>()
using(System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
while(!file.EndOfStream) lines.Add(file.ReadLine());
}
lines
列表来创建你的数组。对于较大的文件可能有更有效率的方法,但您可以从以下方式开始:
int l_rowCount = 0;
string l_path = @"C:\Path\To\Your\File.txt";
using (StreamReader l_Sr = new StreamReader(l_path))
{
while (l_Sr.ReadLine())
l_rowCount++;
}
你能否尝试使用更加高级的语句,比如Linq语句?
类似于从文本文件中计算行数的语句:
Count * from textfile
你觉得呢?