Count lines in a text file

I am coding in C # and using Windows Forms. I have a text file and you want to count all the lines that are in it.

Peter 25

John; 31

Jane, 22

These are three lines, and I want to count them, for example.

+5
source share
3 answers

A better way would be to use something like:

var count = File.ReadLines("file.txt").Count();

This will only work in .NET 4, but will read one line at a time. If you are happy enough to load the entire file into memory in one go, you can use:

var count = File.ReadAllLines("file.txt").Length;

Please note that if the file is large (or it is on a network drive, etc.), this can take a lot of time, in which case you will want to do this from the user interface stream.

+6
source

, :

File.ReadAllLines(filePath).Length;

( , , )

+2
        string fileName = @"X:\Testfolder\countthis.txt";
        int lineCount = 0;

        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        StreamReader reader = new StreamReader(fs);
        Assert.Fail();

        while (reader.ReadLine() != null)
            lineCount++;
        return lineCount; 
+1
source

All Articles