Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading