如何在 C# 中编写读取文本文件并输出总行数的程序?

How do I write a program in C# that reads a text file and outputs the total number of lines?

攻读 Web 开发学士学位,我编写了一些代码来读取文本文件并将行添加到我的控制台程序,

我不知道如何编写代码来计算文本文件输出的行数?

我只编写了几个月的代码,任何帮助都会很棒! (代码如下)

static void main(string[] args)
{
    Console.WriteLine("Welcome to reading from files");
    TextReader tr = new StreamReader("C:/Temp/ReadingFromFile.txt");
    String line;
    while ((line = tr.ReadLine()) != null)
    {
       Console.WriteLine(line);
    }
    tr.Close()
    Console.WriteLine("Press any key to continue...")
    Console.ReadKey();
}

您的代码应如下所示:

static void Main(string[] args)
{
    Console.WriteLine("Welcome to reading from files");
    using (var sr = new StreamReader(@"C:\Temp\ReadingFromFile.txt"))
    {
        string line;
        int count = 0;
        while ((line = sr.ReadLine()) != null)
        {
            count++;
            Console.WriteLine(line);
        }
        Console.WriteLine(count);
    }
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey();
}

或者,您可以这样做:

static void Main(string[] args)
{
    Console.WriteLine("Welcome to reading from files");
    foreach (var line in File.ReadLines(@"C:\Temp\ReadingFromFile.txt"))
        Console.WriteLine(line);
    Console.WriteLine(File.ReadLines(@"C:\Temp\ReadingFromFile.txt").Count());
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey();
}