tags:

views:

83

answers:

3

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

+3  A: 

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++;
    }
}
Foole
THis the approach i'm currently using
Fladur
@Fladur your question doesn't explain this clearly. I don't think I deserve -1.
Foole
From my post:without having to check until the line is empty (My current approach)?You just copy pasted some code
Fladur
Lesson learned. Don't try to help people who don't post code.
Foole
Fladur you asked for the appropiate way of reading the number of lines. cxfx gave you a 1-liner that loads the whole file into the memory at once which makes it unsuitable for larger files. Foole's answer on the other hand only uses the amount of memory equal to the longest line in the file which in almost all cases won't be noticeable.
Qua
Btw, an even more efficient way to do this would be to read character by character checking for newlines and never build the line strings.
Foole
+1 ridiculous to downvote this, current approach wasn't given in the question.
cxfx
It's subjective, You are right, sorry, please edit something in your question so that I can remove my vote.
Fladur
+2  A: 

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

johnc
+2  A: 
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 != "");
cxfx
ReadAllLines is very inefficient for large files as it reads the entire file in to memory.
Foole
Downvoted for the reason given by Foole.
Qua
@Foole @Qua That's true; however, the question asks for the 'proper' way, which would be different based of the size of file you're expecting. It's subjective.
cxfx
@cxfx Agreed. I was just adding information.
Foole