When I create try to read lines like this, Stream.Position changes one time after first call to StreamReader.ReadLineAsync and then doesn't change after any number of calls.
var stream = new FileStream(
filename,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true);
using (var sr = new StreamReader(stream))
{
while(stream.Position <= stream.Length)
{
var pos = stream.Position;
var line = sr.ReadLineAsync().Result;
Console.WriteLine("{0}: {1}", pos, line);
}
}
When I run this, given input
1 2 3
4 5 6
7 8 9
10 11 12
It gives me output
0: 1 2 3
29: 4 5 6
29: 7 8 9
29: 10 11 12
29:
29:
And so on.
StreamReader.ReadLine
(and equivalently ReadLineAsync
) will often read more than just a single line - it basically reads into a buffer and then interprets that buffer. That's much more efficient than reading a single byte at a time, but it does mean that the stream will have advanced further than it strictly speaking needs to.
Basically, I wouldn't try to use Stream.Position
for a stream which is wrapped by another object (e.g. BufferedStream
, StreamReader
etc). The buffering will make things confusing.
See more on this question at Stackoverflow