There is no public methods to reset this encoding and preamble state so the safest thing to do if you need to "rewind" a stream reader is to seek the underlying stream to the beginning (or set position) as shown and create a new StreamReader , just calling DiscardBufferedData() on the StreamReader will not be ...
StreamReader. ReadLine() method reads a line of characters from the current stream and returns the data as a string.
StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file. Important. This type implements the IDisposable interface.
A StreamReader is used whenever data is required to be read from a file. A Streamwriter is used whenever data needs to be written to a file.
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
I use this method:
System.IO.StreamReader reader = new System.IO.StreamReader("file.txt")
//end of reading
reader.DiscardBufferedData();
reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
Amy's answer will work on some files but depending on the underlying stream's encoding, you may get unexpected results.
For example if the stream is UTF-8 and has a preamble, then the StreamReader
will use this to detect the encoding and then switch off some internal flags that tells it to detect the encoding and check the preamble. If you reset the stream's position to the beginning, the stream reader will now consume the preamble again but it will include it in the output the second time. There is no public methods to reset this encoding and preamble state so the safest thing to do if you need to "rewind" a stream reader is to seek the underlying stream to the beginning (or set position) as shown and create a new StreamReader
, just calling DiscardBufferedData()
on the StreamReader
will not be sufficient.
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.
public long ReadList(string fileName, Action<string> action,long position=0)
{
if (!File.Exists(fileName)) return 0;
using (var reader = new StreamReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),System.Text.Encoding.Unicode))
{
if (position > 0)reader.BaseStream.Position = position;
while (!reader.EndOfStream)
{
action(reader.ReadLine());
}
return reader.BaseStream.Position;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With