C# 如何提取字符串标记指定范围内的文本文件内容

C# 如何提取字符串标记指定范围内的文本文件内容,c#,text-files,text-extraction,C#,Text Files,Text Extraction,我有一个控制台文件, 我需要匹配一个字符串(“Seq start”),如果我得到该字符串,我想复制所有文本,直到在txt文件中得到另一个字符串(“Seq end”) // 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:\User

我有一个控制台文件, 我需要匹配一个字符串(“Seq start”),如果我得到该字符串,我想复制所有文本,直到在txt文件中得到另一个字符串(“Seq end”)

// 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.
       }
    }
检查下面链接中的第二个示例- 你可以用这个

我们加载文件和解析行来搜索开始和结束序列,假设每个序列只允许一个

然后,如果找到了正确的部分,我们将使用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}.");
  }
}
使用System.Linq;
使用System.Collections.Generic;
静态孔隙试验()
{
字符串分隔符start=“Seq start”;
字符串分隔符rend=“Seq end”;
字符串filenameSource=“c:\\sample source.txt”;
字符串filenameDest=“c:\\sample dest.txt”;
var result=新列表();
var lines=File.ReadAllLines(filenameSource);
int indexStart=-1;
int indexEnd=-1;
对于(int index=0;index
可以有多个“Seq start”。我想要第一个“Seq start”并继续,直到“Seq End”不出现。你能帮我吗?我是c#的新手。