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


当前回答

计算回车/换行次数。我相信在unicode中它们仍然分别是0x000D和0x000A。这样你就可以根据自己的意愿来决定是否要同时处理两个角色

其他回答

严重迟到的编辑:如果您使用的是。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可能对小文件更快,但对大文件明显更慢;尽管唯一的方法是用秒表或代码分析器来测量。

try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         

如果你说的简单是指易于破译但效率很低的代码行?

string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();

这可能是知道行数的最快方法。

你还可以这样做(取决于你是否在缓冲它)

#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}

还有许多其他的方法,但上面的一种可能是你会选择的。

这将使用更少的内存,但可能需要更长的时间

int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
  count++;
}
reader.Close();

最简单的:

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