2010-02-18 23 views

回答

3
long size = (new FileInfo(myFile)).Length; 
int rows = File.ReadAllLines(myFile).Length; //for smaller files 
2
string filePath; 
int fileSize; 
int fileLines 

文件大小

fileSize = File.OpenRead(path).Length; 

行数

fileLines = File.ReadAllLines(path).Length; 

或者

using (TextReader reader = File.OpenText(path)) { 
while (reader.ReadLine() != null) 
{ 
lines++; 
} 
+0

var'只是好奇你为什么要在这里使用它,它不容易阅读,在我看来是一个坏习惯。 – 2010-02-18 20:00:48

+0

http://meta.stackexchange.com/questions/19568/can-we-stop-with-the-constant-overuse-of-var-on-so – 2010-02-18 20:03:02

+0

进行了更正。感谢您指出 – 2010-02-18 20:06:34

1

如果你有一个巨大的文件,所有你关心的是行数,你不需要将其加载到内存中,只需使用StreamReader

long count = 0; 
using (StreamReader r = new StreamReader("file.txt")) 
{ 
    string line; 
    while ((line = r.ReadLine()) != null) 
    { 
     count++; 
    } 
} 
+2

是不是不必要的?我的意思是,你可以直接检查'ReadLine()'对'Null'。 – Bobby 2010-02-18 20:18:05

相关问题