C# StreamReader 可以检查当前行号吗?

C# Can StreamReader check current line number?

我尝试编写一个脚本来逐行读取 TXT 文件,并根据文件内容更改标签。 有没有办法检查正在读取哪一行?

此示例使用 StreamReader 的 ReadLine 方法将文本文件的内容一次一行读入字符串 class,您只需检查行字符串并与您想要的标签匹配并替换为那个。

int counter = 0;  
string line;  

System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine(line);  
    counter++;  
}  

file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);  

System.Console.ReadLine(); 

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string fileName = @"C:\some\path\file.txt";

        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

希望对您有所帮助。

您可以尝试在 Linq 的帮助下查询 文件:

  using System.IO;
  using System.Linq;

  ...

  var modifiedLines = File
    .ReadLines(@"c:\myInitialScript.txt") // read file line by line
    .Select((line, number) => {
       //TODO: relevant code here based on line and number

       // Demo: return number and then line itself
       return $"{number} : {line}";
     })
    // .ToArray() // uncomment if you want all (modified) lines as an array 
     ; 

如果要将修改后的行写入文件:

  File.WriteAllLines(@"c:\MyModifiedScript.txt", modifiedLines);

如果你坚持StreamReader,你可以实现一个for循环:

  using (StreamReader reader = new StreamReader("c:\myInitialScript.txt")) {
    for ((string line, int number) record = (reader.ReadLine(), 0); 
          record.line != null; 
          record = (reader.ReadLine(), ++record.number)) {
      //TODO: relevant code here
      //     record.line - line itself
      //   record.number - its number (zero based)
    }
  }