tags:

views:

384

answers:

3

I'm reading a file in line-by-line and I want to be able to restart the read by calling a method Rewind().

How can I manipulate my System.IO.StreamReader and/or its underlying System.IO.FileStream to start over with reading the file?

I got the clever idea to use FileStream.Seek(long, SeekOffset) to move around the file, but it has no effect the enclosing System.IO.StreamReader. I could Close() and reassign both the stream and the reader referecnes, but I'm hoping there's a better way.

A: 

StreamReader has a property BaseStream that could be used to access real stream.

If the BaseStream is seekeable (CanSeek property) you could set the Position property to 0 to restart the stream.

Hope it helps

Limo Wan Kenobi
As @yodaj007 points out, you need to discard StreamReader's buffer.
Mehrdad Afshari
Yep, I must admit I didn't think about it. Yoda is right. (Too much Star Wars in this question, don't you think? ;P)
Limo Wan Kenobi
+8  A: 

You need to seek on the stream, like you did, then call DiscardBufferedData on the StreamReader. Documentation here:

Edit: Adding code example:

Stream s = new MemoryStream();
StreamReader sr = new StreamReader(s);
// later... after we read stuff
s.Position = 0;
sr.DiscardBufferedData();        // reader now reading from position 0
yodaj007
+1  A: 

This is all good if the BaseStream can actually be set Position property to 0.

If you cannot (example would be a HttpWebResponse stream) then a good option would be to copy the stream to a MemoryStream...there you can set Position to 0 and restart the Stream as much as you want.

bojanskr