我试图计算txt文件中的所有行,我使用StreamReader:
public int countLines(string path)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
int nlines=0;
string line;
StreamReader file = new StreamReader(path);
while ((line = file.ReadLine()) != null)
{
nlines++;
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.Write(elapsedMs)
// elapsedMs = 3520 --- Tested with a 1.2 Mill txt
return nlines;
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来计算行数?