Chris Chris - 3 years ago 105
C# Question

Return StreamReader to Beginning

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


How can I manipulate my
and/or its underlying
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
. I could
and reassign both the stream and the reader referecnes, but I'm hoping there's a better way.

Amy Amy
Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download