是否有一种简单的方法来编程确定文本文件中的行数?


当前回答

最简单的:

int lines = File.ReadAllLines("myfile").Length;

其他回答

严重迟到的编辑:如果您使用的是。net 4.0或更高版本

File类有一个新的ReadLines方法,它懒惰地枚举行,而不是贪婪地将它们全部读入ReadAllLines这样的数组。所以现在你可以用下面的方法既高效又简洁:

var lineCount = File.ReadLines(@"C:\file.txt").Count();

原来的答案

如果你不太在意效率,你可以这样写:

var lineCount = File.ReadAllLines(@"C:\file.txt").Length;

对于一个更有效的方法,你可以这样做:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}

编辑:在回答有关效率的问题时

The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).

在速度方面,我不期望它有很多。ReadAllLines可能有一些内部优化,但另一方面,它可能必须分配大量内存。我猜ReadAllLines可能对小文件更快,但对大文件明显更慢;尽管唯一的方法是用秒表或代码分析器来测量。

您可以快速地读入它,并增加一个计数器,只需使用一个循环来增加,对文本不做任何操作。

您可以启动“wc.exe”可执行文件(UnixUtils附带,不需要安装)作为外部进程运行。它支持不同的行数方法(如unix vs mac vs windows)。

最简单的:

int lines = File.ReadAllLines("myfile").Length;

一个可行的选择,也是我个人使用过的,就是在文件的第一行添加您自己的头文件。我为自己的游戏定制模型格式。基本上,我有一个工具来优化我的.obj文件,去掉我不需要的垃圾,将它们转换为更好的布局,然后在第一行上写入行、面、法线、顶点和纹理uv的总数。当模型加载时,这些数据将被各种数组缓冲区使用。

这也很有用,因为您只需要循环文件一次来加载它,而不是一次来计算行数,然后再次将数据读入创建的缓冲区。