When I'm using a Text reader what is the best way to detect that I am actually at the end of my data? The usual way to do this is something like the following,
while(reader.Peek() != -1)
{
///do stuff
}
However the msdn documentation here states the following
An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking.
So my question is how do you tell if you are really at the end of the readers data or the reader/underlying stream simply doesn't support seeking as the return value here seems to be ambiguous? if for example I have the following
public void Parse(TextReader reader)
{
while(reader.Peek() != -1) //am I really at the end
{
//do stuff
}
}
Parse(new StreamReader(new NetworkStream(....)));
as networkstream does not support seeking.
Or have I missed something?
Edit:
Just to clarify, I can easily implement this using the more specific StreamReader class, as I can check for EoS. However to keep things more general, I wanted to use TextReader so I am not tied to just StreamReader. However the semantics of Peek seem a little odd, why does it not just throw if seeking isnt supported, and to this end why isn't there an EoF property for TextReader?
Peek
instead ofRead
? – Grussingreader.BaseStream.CanSeek
then? – Grussing.Peek
and not.EndOfStream
to check if the End of the Stream is reached? Is there any advantage using.Peek
? – Gurnard