You should be able to use
myStreamReader.BaseStream.Position = desiredPosition;
myStreamReader.DiscardBufferedData();
to move the stream to a specific place.
EDIT: The next question is how to find the desiredPosition
. Since you want to move the position back through the file, not forward, it follows that you have read each position at some point. You need to keep track of where you are in the stream as you read your lines, and store positions in a List<int> positions
. Initially, the list should contain 0
at position zero. As you process lines, add the length of the line plus the size of line break to the list. When you want to go back to line k
, positions[k]
should have the position you need.
For example, if your file has the lines below, your encoding uses one character per letter, and the line separator in the file is Windows-style \r\n
Quick
brown fox
jumps over lazy
dog
then your positions
list should have {0, 7, 17, 34}
Note that I added 2 on each line for the separator characters.
P.S. This is an ugly solution, isn't it? If it is any comfort, you are not the first person who ran into it. Here is a somewhat obscene rant from someone who wanted to solve a similar problem back in 2007.