Can't understand why StreamReader.Peek reader returns -1!

  • Thread starter Thread starter Carl Johansson
  • Start date Start date
C

Carl Johansson

Please ponder the following method which demonstrates my question:

private static void DemoPeekQuestion()
{
using (StreamReader streamReader = File.OpenText(@"sometext.txt"))
{
// Read to end of stream.
string s = streamReader.ReadToEnd();

// Peek!
streamReader.BaseStream.Position = 0;
// bool b = streamReader.EndOfStream; // Uncomment for different
Peek() return value.
int i = streamReader.Peek();
Console.Write("- i - = {0}", i);
Console.ReadLine();
}
}

Even though the Position property has been assigned 0, the Peek() method
returns -1. However, when I uncomment the statement:

bool b = streamReader.EndOfStream;

Peek() returns a value greater than -1.

Any ideas, anyone?

Regards Carl Johansson
 
Carl said:
Please ponder the following method which demonstrates my question:

private static void DemoPeekQuestion()
{
using (StreamReader streamReader = File.OpenText(@"sometext.txt"))
{
// Read to end of stream.
string s = streamReader.ReadToEnd();

// Peek!
streamReader.BaseStream.Position = 0;
// bool b = streamReader.EndOfStream; // Uncomment for different
Peek() return value.
int i = streamReader.Peek();
Console.Write("- i - = {0}", i);
Console.ReadLine();
}
}

Even though the Position property has been assigned 0, the Peek() method
returns -1. However, when I uncomment the statement:

bool b = streamReader.EndOfStream;

Peek() returns a value greater than -1.

Any ideas, anyone?
You must call StreamReader.DiscardBufferedData() when changing the
underlying stream's position directly. The StreamReader cannot detect this
on its own and Bad Things can happen if you continue reading without doing
that. Reading .EndOfStream has the side effect of refilling the reader's
buffer, which is why it also happens to change what .Peek() returns, but
this is a coincidence and not something to rely on.
 
Back
Top