The goal is to be able to close the stream and return to the same position (as a "bookmark").
Edit: two users suggested that I had to use streamReader.DiscardBufferedData()
, and that at least made Test1
and Test2
react the same way. I've erased Test2
(for info: it was the exact same code as Test1
, but closing and re-opening the stream), and "repaired" Test1
:
Test1
still fails:
public static void Test1(string filePath)
{
var line1 = default(string);
var line2 = default(string);
var line3 = default(string);
using (StreamReader streamReader = File.OpenText(filePath))
{
// read 2 consecutive lines:
line1 = streamReader.ReadLine();
var line2StreamPosition = streamReader.BaseStream.Position; // save position at the begining of line2:
line2 = streamReader.ReadLine();
// go back to the position of line2 and try to re-read it:
streamReader.DiscardBufferedData();
streamReader.BaseStream.Seek(line2StreamPosition, SeekOrigin.Begin);
line3 = streamReader.ReadLine();
if (line2 == line3)
{
// it doesn't reach this point
}
else
{
// it fails ...
// it starts reading `line3` at an incorrect position
}
}
}
Also: var canSeek = streamReader.BaseStream.CanSeek; // true
.