Count file lines in C#
I want to know how many lines I have in my file. How can I do it in a simple way (I mean, not to go through on all over the file and count each line)? Is there a command for that?开发者_如何学C
Well:
int lines = File.ReadAllLines(path).Length;
is fairly simple, but not very efficient for huge text files. I'd probably use a TextReader
in most cases, to avoid excessive buffering:
int lines = 0;
using (TextReader reader = File.OpenText(path)) {
while (reader.ReadLine() != null) { lines++; }
}
Any "function" you call is going to essentially do the same thing -- go line by line and count the number of new line characters.
If you want to decieve yourself into making something seem more "crisp" a regex expression to count the number of new line characters would do the trick.
One way or another (Regex, FileStream etc.) something, somewhere will have to go through the newlines.
Depends on the length of the line...usually the fastest way is to do this using this simple formula - get the length of the file in bytes and divided by the length of the line, for example:
const int LINE_LENGTH = 80; System.IO.FileInfo f = new System.IO.FileInfo(path); int noLines = f.Length / LINE_LENGTH;
The above assumes the length of the line is a constant 80 characters wide...
If the length is variable, there is no other way of doing it, apart from opening the file and iterate through each line and keep track of the line count.
Edit:
I just realized a much easier way after I posted a comment below..
Would it not be easier to actually use the Shell under System.Diagnostics.Process
namespace to invoke grep -c "$(\r?\n?|\n)"
using an argument as the path to the file in question - this would make it more flexible and can cater for any file. The only thing you would have to do is read in the output and regex it to get at the actual number of lines, for instance, using my grep that came with Borland C, I get this output
C:\Documents and Settings\Tom>grep -c "$(\r?\n?)" 273.txt File 273.txt: 35 lines match
The output and mileage may vary, the -c
command switch to grep means 'count of'
精彩评论