Search code examples
c#counter

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


Studying a bachelor on Web Development, I've written some code which reads a text file and adds the lines to my console program,

I'm stuck on how I would write the code to count the amount of lines the text file outputs?

I've only been coding for a couple of months, any help would be great! (code is below)

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();
}

Solution

  • Your code should look like this:

    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();
    }
    

    As an alternative, you could do this:

    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();
    }