2010-02-18 63 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

相關問題