如何在C#中获取文件中的行数?

7

我需要初始化一个二维数组,并将文件中的每一行作为第一列。如何获取文件中的行数?

7个回答

15

你可以这样做:

System.IO.File.ReadAllLines("path").Length

编辑

正如Joe所指出的那样,我省略了所有标准错误处理,并且没有展示您将如何在其余代码中使用此相同的数组进行处理。


点赞 ReadAllLines,但实际上我会把数组保存在某个地方,因为他很快就会再次需要它,并检查已保存数组的长度。 - Joel Coehoorn
我正在编辑一个CYA条款,但我把所有的都遗漏了,然后选择不加入...看来我应该这么做。谢谢。 - JoshBerke
只要小心文件大小和ReadAllLines,就可以避免内存问题。虽然在这个问题中并不适用,因为整个文件都将被读取。但通常需要注意这一点,特别是如果您无法控制文件的大小。 - Richard

7

来自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();

6

为获取计数,您需要逐行打开读取文件:

var lines = File.ReadAllLines(filename);
var count = lines.Length;

4
int counter = 0;
string line;

System.IO.StreamReader file = new System.IO.StreamReader("c:\\t1.txt");
while((line = file.ReadLine()) != null)
{
    counter++;
}
file.Close();

计数器将给出行数。您可以使用循环将行插入到数组中。


2
@Mutant:如果你将文件放入using块中,你会获得更多的赞。 - John Saunders

2

你最好打开文件,将每一行读入一个列表中,然后创建你的二维数组,这样会更加实用。

List<string> lines = new List<string>()

using(System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
    while(!file.EndOfStream) lines.Add(file.ReadLine());
}

你可以使用你的 lines 列表来创建你的数组。

2

对于较大的文件可能有更有效率的方法,但您可以从以下方式开始:

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++;
}

-1

你能否尝试使用更加高级的语句,比如Linq语句?

类似于从文本文件中计算行数的语句:

Count * from textfile

你觉得呢?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接