MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.
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 ...
The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty.
When you read a stream to the end, specifically with StreamReader
's ReadToEnd
method, you have to Seek
it back to the beginning. This can be done like so:
StreamReader sr = new StreamReader(stream);
sr.ReadToEnd();
stream.Seek(0, SeekOrigin.Begin); //StreamReader doesn't have the Seek method, stream does.
sr.ReadToEnd(); // This now works
Your conclusion is correct; once you've reached the end of your stream, you won't be able to read more data until you've reset your position within the stream:
myStream.Position = 0;
This is equivalent to seeking back to the beginning. Note that your stream must support seeking for this to work; not all streams do. You can check this with the CanSeek
property.
Use BaseStream
for StreamReader
:
StreamReader sr = new StreamReader(pFileStream);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
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