How to transparently track line numbers from a character stream in C #?

I would like to find an arbitrary point in the character stream, and then get the corresponding line number. In Java, this can be handled transparently using the java.io.LineNumberReader.getLineNumber () method.

What is the best way to do this in C #?

+4
source share
3 answers

There is nothing like this in .NET. Use the ReadLine () method and track line numbers yourself.

+3
source

One possible solution would be to get your own stream class and override the read / write / write functions so that you can track new lines yourself. Another possible solution is a method that works with a thread to do what you want:

static int LineNumber(System.IO.Stream s) { byte[] buffer = new byte[s.Length]; s.Read(buffer, 0, (int)s.Length); string text = System.Text.Encoding.ASCII.GetString(buffer); int idx = 0; int line = 0; do { idx = text.IndexOf('\n', idx); if (idx > -1) { line++; if (s.Position <= idx) return line; if (idx < text.Length - 1) idx++; } else { if (line > 0) return line; else break; } } while (true); return 1; } 
0
source

Java probably developed a stateful text reader and .NET will run it over the next 10 years.

If you are not going to wait, you should write a wrapper class (stateful) around the .NET TextReader Class, which adds the desired functionality to the class. You just need to count the newline characters as the stream goes forward. Obviously, this class will be slower than the original class, so making this function optional is a good idea.

0
source

All Articles