Как извлечь содержимое текстового файла в области, ограниченной строковым маркером - PullRequest
0 голосов
/ 01 октября 2019

У меня есть файл консоли, мне нужно сопоставить строку ("Seq Started"), и если я получаю строку, я хочу скопировать весь текст, пока не получу другую строку ("Seq Ended") в текстовом файле.

Ответы [ 2 ]

0 голосов
/ 01 октября 2019

Вы можете использовать это.

Мы загружаем файл и анализируем строки для поиска последовательности начального и конечного разделителей, предполагая, что разрешена только одна из каждой из них.

Тогда, если разделОбнаружена правильная ошибка, мы извлекаем строки с помощью Linq и сохраняем результат в желаемом файле.

using System.Linq;
using System.Collections.Generic;

static void Test()
{
  string delimiterStart = "Seq Started";
  string delimiterEnd = "Seq Ended";
  string filenameSource = "c:\\sample source.txt";
  string filenameDest = "c:\\sample dest.txt";

  var result = new List<string>();
  var lines = File.ReadAllLines(filenameSource);

  int indexStart = -1;
  int indexEnd = -1;
  for ( int index = 0; index < lines.Length; index++ )
  {
    if ( lines[index].Contains(delimiterStart) )
      if ( indexStart == -1 )
        indexStart = index + 1;
      else
      {
        Console.WriteLine($"Only one \"{delimiterStart}\" is allowed in file {filenameSource}.");
        indexStart = -1;
        break;
      }
    if ( lines[index].Contains(delimiterEnd) )
    {
      indexEnd = index;
      break;
    }
  }

  if ( indexStart != -1 && indexEnd != -1 )
  {
    result.AddRange(lines.Skip(indexStart).Take(indexEnd - indexStart));
    File.WriteAllLines(filenameDest, result);
    Console.WriteLine($"Content of file \"{filenameSource}\" extracted to file {filenameDest}.");
  }
  else
  {
    if ( indexStart == -1 )
      Console.WriteLine($"\"{delimiterStart}\" not found in file {filenameSource}.");
    if ( indexEnd == -1 )
      Console.WriteLine($"\"{delimiterEnd}\" not found in file {filenameSource}.");
  }
}
0 голосов
/ 01 октября 2019
// Read each line of the file into a string array. Each element
    // of the array is one line of the file.
    string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

    // Display the file contents by using a foreach loop.
    System.Console.WriteLine("Contents of WriteLines2.txt = ");
    foreach (string line in lines)
    {
       if(line == "Seq Started" && line != "Seq Ended")
       {
        //here you get each line in start to end one by one.
        //apply your logic here.
       }
    }

Проверьте второй пример в приведенной ниже ссылке - [https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file][1]

...