Tracking the position of the line of a streamreader

johnnie picture johnnie · Apr 17, 2012 · Viewed 22.3k times · Source

I need to track the position of the line that I am reading from the stream reader. When I say reader.ReadLine(), I need to know the position of that line in the file and I also want to be able to then read the file from the position I have previously tracked.

Is this possible?

Answer

Chris Gessler picture Chris Gessler · Apr 17, 2012

You can do this one of three ways:

1) Write your own StreamReader. Here's a good place to start: How to know position(linenumber) of a streamreader in a textfile?

2) The StreamReader class has two very important, but private variables called charPos and charLen that are needed in locating the actual "read" position and not just the underlying position of the stream. You could use reflection to get the values as suggested here

Int32 charpos = (Int32) s.GetType().InvokeMember("charPos", 
BindingFlags.DeclaredOnly | 
BindingFlags.Public | BindingFlags.NonPublic | 
BindingFlags.Instance | BindingFlags.GetField
 ,null, s, null); 

Int32 charlen= (Int32) s.GetType().InvokeMember("charLen", 
BindingFlags.DeclaredOnly | 
BindingFlags.Public | BindingFlags.NonPublic | 
BindingFlags.Instance | BindingFlags.GetField
 ,null, s, null);

return (Int32)s.BaseStream.Position-charlen+charpos;

3) Simply read the entire file into a string array. Something like this:

char[] CRLF = new char[2] { '\n', '\r' };
TextReader tr = File.OpenText("some path to file");
string[] fileLines = tr.ReadToEnd().Split(CRLF);

Another possibility (along the sames lines as #3) is to read in the lines and store the line in an array. When you want to read the prior line, just use the array.