-1

Scenario:

  • I got a .txt File with 10 lines of text.
  • I have two Streamreaders (reader1, reader2).
  • I want reader1 to read the lines 1-6
  • After that I want reader2 to read the lines 7-10

Therefore I need to get the last position of reader1 and I have to start reader2 at the same position plus one.

Is this possible with Streamreader? Are there any "positions", indexes or something similar which could help me to navigate trough the .txt file.

k.troy2012
  • 344
  • 4
  • 21
  • 1
    This sounds like an XY problem...what is the larger scenario you're trying to fulfill here? – Rufus L Nov 14 '18 at 18:11
  • You can always do `var firstPart = File.ReadLines(filePath).Take(6); var secondPart = File.ReadLines(filePath).Skip(6).Take(4);`, but it would be more efficient to first take all 10 and then split them up. – Rufus L Nov 14 '18 at 18:12
  • Not a great method. There are much better ways of parsing a text file. – jdweng Nov 14 '18 at 18:12
  • Like @RufusL, I am curious why you want to do this. But, if you construct your `StreamReader` on a `Stream` (or pull out the underlying stream with the `BaseStream` property), you *should* be able to play position games on that stream. No guarantees it will work though. – Flydog57 Nov 14 '18 at 18:16
  • This is a poor approach, and I see totally no use for it. You should read the file linearly, using one StreamReader. – Nick Nov 14 '18 at 18:21
  • Is your criteria for splitting 1-6 and 7-10 some sort of string/character delimiter? Because as the others have alluded to, file I/O is probably one of, if not the, slowest operation you will perform in programming. Therefore, whenever you're reading/writing to a file, you should try to do as *least* amount of IO as possible. If you ever get around to exporting Excel spreadsheets, you'll notice extremely fast how efficent things will become when you read/write once. – Chris Nov 14 '18 at 19:11
  • So with that being said, do yourself a favor -- Read everything once, and then split your message based on whatever delimiter you designate. I imagine you aren't just picking arbitrary lines to read from, so there has to be a distinction somewhere that you can split, right? – Chris Nov 14 '18 at 19:13

1 Answers1

1

Using technique mentioned here ,You can do something like this

StreamReader r1;
StreamReader r2;
string file="filepath.txt";

ReadLine(file,1,6,ref r1);
ReadLine(file,7,10,ref r2);
string ReadLine(string fileName, int start,int end,ref StreamReader rdr)
{
   try{
       using (rdr = new StreamReader(fileName)) {
      for (int i = start; i <=end; i++)
      rdr.ReadLine();
      return sr.ReadLine();
      }
}
    catch(Exception ex)
    {
     }
}
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66