0

I was just learning and had a problem working with files. I have a method that has two inputs, one at the beginning of the line (lineStart) I want and the other at the end of the line (lineEnd) I need method that extract between these two numbers for me and write on file .

ex ) lineStart = 20 , lineEnd = 90, in output Must be = 21-89 line of txt file.

          string[] lines = File.ReadAllLines(@"");

        int lineStart = 0;
        foreach (string line0 in lines)
        {
            lineStart++;
            if (line0.IndexOf("target1") > -1)
            {
                Console.Write(lineStart + "\n");
            }
        }
           int lineEnd = 0;

         foreach (string line1 in lines)
            {
                lineEnd++;
                if (line1.IndexOf("target2") > -1)
                {
                    Console.Write(lineEnd);
                }
            }

        // method grabText(lineStart,lineEnd){}

enter code here
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

1

It is just a line of code

string[] lines = File.ReadLines(@"").Skip(lineStart).Take(lineEnd-lineStart);

Notice also that I use ReadLines and not ReadAllLines. The first one doesn't load everything in memory.
It is not very clear what are the boundary of the lines to take but of course it is very easy to adapt the calculation

Steve
  • 213,761
  • 22
  • 232
  • 286
  • thx . but it just read from input . i want to read from huge text and then fetch these lines and write in .txt file – TonyIsHere Aug 10 '21 at 07:51
  • As I have told you ReadLines doesn't load all the lines in memory but read them one by one See https://stackoverflow.com/questions/21969851/what-is-the-difference-between-file-readlines-and-file-readalllines – Steve Aug 10 '21 at 08:45
0

If your text file is huge, don't read it into memory. Don't look for indexes either, just process it line by line:

bool writing = false;

using var sw = File.CreateText(@"C:\some\path\to.txt");

foreach(var line in File.ReadLines(...)){ //don't use ReadAllInes, use ReadLines - it's incremental and burns little memory

  if(!writing && line.Contains("target1")){
    writing = true; //start writing
    continue; //don't write this line
  }

  if(writing){
    if(line.Contains("target2"))
      break; //exit loop without writing this line
    sw.WriteLine(line);
  }
}
Caius Jard
  • 72,509
  • 5
  • 49
  • 80