I'm doing some tests, and swapping out a Stream that usually comes from a web request with a stream I have created.
I create the stream like this:
MemoryStream responseDataStream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(responseDataStream))
{
sw.Write(responseData);
sw.Flush();
sw.Close();
}
However when my code tries to consume it:
StreamReader reader = new StreamReader(myStream);
I get the error Stream was not readable.
I want to prepare my stream so that it is ready to be consumed. How can I do this?
By default, StreamWriter takes ownership of the stream you pass in the constructor. When the stream writer is closed, it will close the underlying stream as well. You need to use a different overload of the constructor, e.g. new StreamWriter(responseDataStream, Encoding.UTF8, true).
Second, the stream is still at the position of the last write. You need to rewind it:
responseDataStream.Position = 0;
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