0

I would like to ask if there is any posibility to read previous lines (or chars) with StreamReader.

My problem is that I am reading pretty big file (even GBs) but sometimes I want to go back to previous (second) '#' (it should be usually in 10k chars far). So I wanted to seek somehow back. Hovewer, StreamReader.BaseStream.Seek() doesnt move a pointer anywhere and when I call Peek() again there is no change in reading.

Is there some way to do that?

My code:

int counterOfSharps = 0;
while(counterOfSharps < 2 && streamReader.BaseStream.Position > 0){
    streamReader.BaseStream.Position = streamReader.BaseStream.Seek(-1, SeekOrigin.Current);
    if (streamReader.Peek() >= 0 && Convert.ToChar(streamReader.Peek()) == '#')
    counterOfSharps++;
}

So changing position by -1 to get previous char, but the only thing is changing is position, but Peeking is still getting former char.

  • Seeking a `StreamReader` is problematic on the best of days because of various encoding. However, if you can show your code in a [mcve] and the problem you are trying to solve specifically, there maybe other solutions or approaches you haven't thought of – TheGeneral Dec 05 '20 at 00:17
  • Have a look at [this related question](https://stackoverflow.com/questions/2053206/return-streamreader-to-beginning). – Axel Kemper Dec 05 '20 at 00:18
  • 1
    Can you show some of the code you have already. How large is your "large" file. How far back do you anticipate you MAY need to look backwards... 100 chars, 500 chars, 2k? At what point. If you can also provide SAMPLE of what you are trying to parse while reading might help other alternatives. Please edit your existing post and provide more details instead of comment reply. – DRapp Dec 05 '20 at 02:05
  • 1
    You could remember everything read since the last '#' in an extra buffer while reading the stream. If you need to go back, first use the extra buffer before proceeding from the stream. This avoids the problematic Seek, but is a bit complicated to get it right. – Klaus Gütter Dec 05 '20 at 06:06

0 Answers0