StreamReader and Peek()

D

Dan

Hi, I'm having a problem with StreamReader.Peek(). Let's say I open a file
and read it to end; then I'd want to move its stream pointer back to the
file beginning: I can call BaseStream Seek method or change the value of the
Position property, but this does not seem to affect the Peek() method, which
keeps returning -1 as if it had not been notified that the stream pointer
has been repositioned to file beginning. How can I let Peek() work as
expected (i.e. return a value >=0 once the stream has been repositioned)?

Here's a sample code to reproduce my issue. Thx to all!

StreamReader sr = new StreamReader("c:\\work\\somefile.txt"))
Debug.Assert(sr.Peek()>-1); // OK
sr.ReadToEnd();
Debug.Assert(sr.Peek()==-1); // OK
sr.BaseStream.Seek(0L, SeekOrigin.Begin); // or
sr.BaseStream.Position = 0L;
Debug.Assert(sr.Peek()>-1); // ASSERTION FAILS!!!
 
J

Jon Skeet [C# MVP]

Dan said:
Hi, I'm having a problem with StreamReader.Peek(). Let's say I open a file
and read it to end; then I'd want to move its stream pointer back to the
file beginning: I can call BaseStream Seek method or change the value of the
Position property, but this does not seem to affect the Peek() method, which
keeps returning -1 as if it had not been notified that the stream pointer
has been repositioned to file beginning. How can I let Peek() work as
expected (i.e. return a value >=0 once the stream has been repositioned)?

Use StreamReader.DiscardBufferedData. Basically, StreamReader often
reads more than you ask it to, keeping the read data in a buffer to
make things more efficient. DiscardBufferedData tells it that things
have changed, and it should ignore whatever it had already read.
 

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