Tracking the position of the line of a streamreader

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.

Leave a Comment