C# Может ли StreamReader проверить текущий номер строки? - PullRequest
2 голосов
/ 25 мая 2020

Я пробовал создать сценарий, который будет читать текстовый файл построчно и менять метки в зависимости от того, что находится внутри. Есть ли способ проверить, какая строка читается?

Ответы [ 2 ]

5 голосов
/ 25 мая 2020

В этом примере содержимое текстового файла по одной строке за раз считывается в строку с использованием метода ReadLine класса StreamReader, и вы можете просто проверить строку строки и сопоставить ее с желаемой меткой и заменить ее. 1001 *

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

Надеюсь, это вам поможет.

2 голосов
/ 25 мая 2020

Вы можете попробовать запросить файл с помощью 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 l oop:

  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)
    }
  }      
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...