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

3

我尝试编写一个脚本,按行读取TXT文件,并根据其内容更改标签。

是否有一种方法可以检查正在读取哪一行?


3
在你的程序中加入一个计数器,并在逐行读取循环中对其进行递增。 - Alexey Larionov
目前正在尝试这个。 有点想知道是否有更好的方法。 - JEREDEK
如果有一天有人想要在流中计算单词数,这并不意味着StreamReader必须实现它。它只做它设计的事情 - 按需读取。 - Alexey Larionov
1
@JEREDEK,这不是“粗暴的方式”。你认为什么是最好的呢?其他任何解决方案都会以同样的方式工作,唯一的区别是其他开发人员必须做这项工作 ;) - TinoZ
你可以尝试使用 File.ReadLines(...)Linq,例如 File.WriteAllLines(@"c:\myNewText.txt" File.ReadLines(@"c:\myText.txt").Select((line, number) => /*相关代码在此*/)); - Dmitry Bychenko
2个回答

5

这个例子使用 StreamReader 类的 ReadLine 方法,以字符串的形式逐行读取文本文件内容,并且您可以检查该行字符串是否匹配您想要的标签,然后替换成目标标签。

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);
            }
        }
    }
}

希望这能帮到你。


请勿显式关闭读取器 - file.Close();,而是将其包装在 using 中:using (file = new StreamReader(@"c:\test.txt")) {...} - Dmitry Bychenko
1
@DmitryBychenko,我给了他两个选择,现在由他决定。 - Charanjeet Singh

2
你可以尝试使用 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)
    }
  }      

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接