【问题标题】:Get line number when reading a file读取文件时获取行号
【发布时间】:2017-10-18 17:46:32
【问题描述】:

我正在使用 C# 7 读取文本文件中的所有行,如下所示:

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

  }          
}   

对于每一行,我还需要获取行号。

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

最好的方法是什么?

【问题讨论】:

  • 我不明白什么吗?为什么不能自己数一数呢?

标签: c#


【解决方案1】:

我只是创建一个整数来自己跟踪行号。

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

        lineNumber++;
    }          
}  

Microsoft 还使用这样的变量来计算其中一个示例中的行数:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-a-text-file-one-line-at-a-time

【讨论】:

  • 我相信问题更多是关于这里提到的行号是从文件返回的行的实际索引,而不是增加返回的行数的问题。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      你可以自己计算行号:

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

      【讨论】:

        【解决方案5】:

        我知道这已经解决了,old 但我想分享一个alternative。代码只返回它找到给定字符串的一部分的行号,只需将“包含”替换为“等于”即可。

        public int GetLineNumber(string lineToFind) {        
            int lineNum = 0;
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
            while ((line = file.ReadLine()) != null) {
                lineNum++;
                if (line.Contains(lineToFind)) {
                    return lineNum;
                }
            }
            file.Close();
            return -1;
        }
        

        【讨论】:

          猜你喜欢
          • 2023-03-03
          • 1970-01-01
          • 1970-01-01
          • 2021-06-04
          • 2016-02-21
          • 2012-08-31
          • 1970-01-01
          • 2016-07-04
          • 1970-01-01
          相关资源
          最近更新 更多