Counting lines in a text file

  • Thread starter Thread starter Mark.....
  • Start date Start date
M

Mark.....

Hi,

Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must be
an easier way??

Thanks in advance
 
Mark..... said:
Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must be
an easier way??

I don't see why there "must" be an easier way. Just call ReadLine on a
TextReader until it returns null, incrementing a counter each time. How
could it be much easier?
 
Jon Skeet said:
I don't see why there "must" be an easier way. Just call ReadLine on a
TextReader until it returns null, incrementing a counter each time. How
could it be much easier?

Sorry, that really wasn't meant to come over as aggressively as it did.
Sincere apologies. Put it down to lousy sinuses at the moment :(

(It's still a pretty easy way of counting lines in a file though :)
 
Mark..... said:
Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must
be an easier way??

Hi Mark. A loop is probably the best way to do this, and is really simple.
Because lines are of unpredictable length, without any kind of metadata
stored with the file it's impossible to determine its line count without
reading every byte. If you want to do it in the least possible code, you
could use an expression like this, at the expense of a great deal of
additional memory for large files:

new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
 
new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length

Hehe, I though about suggesting this, but just didn't have the guts to write
such a line of code! :-)
 
All the other comments should be the answer to your literal question.
However, it occured to me, are you trying to get file size? If so there IS a
better way. Take a look at the FileInfo.Length in the System.IO namespace.
 
Back
Top