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 determ开发者_运维问答ine 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
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++;
}
}
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 != "");
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
精彩评论