计算文本文件中的行数,并在1行中计数

所以我想从文本文件中计算它的行​​数,并在控制台窗口的1行中对其进行计数,它可以工作,但是它写了很多行,我希望它每秒钟更改1行。

            long lines = 0;
            using (StreamReader r = new StreamReader("text.txt"))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    count++;
                    Console.Title = "Count: " + lines;
                    Console.WriteLine(Console.Title);
                }
            }

我该如何写成1行而不是很多行?

评论
  • 大白痴
    大白痴 回复

    You can use File.ReadAllLiness(<filePath>).Count() to get count of lines in text file.

    Console.WriteLine(File.ReadAllLiness("text.txt").Count())
    

    Your code is not working because you are printing lines variable which is assigned as 0 at the beginning, but not updated anywhere.

    Either try my first solution or use lines variable instead of count in your existing program and print it out of while loop

    long lines = 0;
    using (StreamReader r = new StreamReader("text.txt"))
    {
        string line;
        while ((line = r.ReadLine()) != null)
        {
            lines++;
          //^^^^^^^ here you need to change
        }
    
       Console.Title = "Count: " + lines;
       Console.WriteLine(Console.Title);
    }