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

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
 
J

Jeroen Mostert

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top