user252778
user252778

Reputation:

Proper way to determine the number of lines in a file in .NET

This questions is really simple, and probably you .NET gurus now the answer =)

So here it comes... What is the proper way (.NET language independent to determine the number of lines (non-blank) exists in a text files without having to check until the line is empty (My current approach)?

Thanks in advance

Upvotes: 1

Views: 198

Answers (3)

johnc
johnc

Reputation: 40223

A file is read in as a stream, so you must read it all to determine what you are trying.

You could scan the bytes, or perform a ReadToEnd on the your FileReader to get the string representation, to find the Environment.NewLine instances and count them.

If you read the file into a string, you have the added benefit of being able to use the Regex classes to count the matches of your Environment.NewLine

EDIT I do like cxfx idea of using File.ReadAllLines and using the resultant Length

Upvotes: 1

Chris Fulstow
Chris Fulstow

Reputation: 41882

var path = @"C:\file.txt";
var lines = File.ReadAllLines(path);
var lineCount = lines.Count(s => s != "");

Or, slightly less readable, all in one go:

var lines = File.ReadAllLines(@"C:\file.txt").Count(s => s != "");

Upvotes: 2

Foole
Foole

Reputation: 4850

Borrowing from here:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while ((string line = reader.ReadLine()) != null)
    {
        if (line.Length > 0) lineCount++;
    }
}

Upvotes: 4

Related Questions