Home > Blockchain >  ReadFile From Certain Lines
ReadFile From Certain Lines

Time:09-26

I want to check for this text (Read) And when it checks for it it reads the lines inside it (Read)

Like this

TXT File:
(
Hi meh
dsa
(Read)
Test Code
Lines
(Read)
hello
sdas
)

Input: File.ReadLines(CodeHere)

Output:

Test Code
Lines

CodePudding user response:

You can implement Finite State Machine (FSM) with 2 state only: should you return current line or not:

  using System.IO;

  ...

  private static IEnumerable<string> MyRead(string fileName) {
    bool inRead = false;

    foreach (string line in File.ReadLines(fileName)) 
      if (string.Equals(line, "(Read)")) 
        inRead = !inRead;
      else if (inRead)
        yield return line; 
  }

Then you can use

  foreach (string line in MyRead(@"c:\MyTest.txt"))
    Console.WriteLine(line); 
  • Related