我如何找出文本文件中的行数?

How do i find out the Number of Lines in a text file?

string s;

Console.WriteLine("Enter What you want to write in your File : ");
s = Convert.ToString(Console.ReadLine());

using (StreamWriter sw = new StreamWriter(@"E:/File.txt"))
{
     sw.Write(s);
     sw.Close();
}

using (StreamReader r = new StreamReader(@"E:/File.txt"))
{
     char[] buffer = new char[1024];
     int read;
     int line = 0;
     while ((read = r.ReadBlock(buffer, 0, buffer.Length)) > 0)
     {
          for (int i = 0; i < read; i++)
          {
               if (buffer[i] == '\n' && buffer[i]=='\r')
               {
                    line++;       
               }
          }               
          //Console.WriteLine(buffer[i]);
     }
     Console.WriteLine("Total Lines Are : " + line);
}

我试图找出总行数,以便我可以更精确地附加它,但我完全做不到。 每当 i 运行 时它输出零。很抱歉成为菜鸟。 :)

你可以这样做:

var lines = File.ReadAllLines(@"E:\File.txt");
Console.WriteLine(lines.Length);

注意:这会将文件的全部内容加载到内存中,所以我认为@Dmitry Bychenko 的回答更好。

为什么不直接

 using System.IO;
 using System.Linq;

 ... 

 int count = File.ReadLines(@"E:\File.txt").Count();