2017-10-18 87 views
-3

当我使用C#7如下读取文本文件中的所有行获取行号:读取文件

using (StreamReader reader = File.OpenText(file)) {  
    String line;  
    while ((line = reader.ReadLine()) != null) { 

    }   
} 

对于每一行我还需要得到行号。

StreamReader似乎没有获取行号的方法。

这样做的最好方法是什么?

+5

我不理解什么吗?你为什么不能自己数数呢? –

回答

2

你应该用你自己的局部变量的话,这样的:

using (StreamReader reader = File.OpenText(file)) {  
     String line;  
     int lineNum=0; 
     while ((line = reader.ReadLine()) != null) { 
     ++lineNum; 
     }   
    } 
0

你可以通过你自己计算行数:

using (StreamReader reader = File.OpenText(file)) {  
    String line; 
    int n = 0; 
    while ((line = reader.ReadLine()) != null) { 
    n++; 
    }   
} 
0

除了其他解决方案在此,我喜欢使用File.ReadAllLines(string)来创建string[]结果,然后使用for (int i = 0; i < result.Length; i++)...