Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a readable Stream?

Tags:

c#

.net

stream

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?

like image 848
NibblyPig Avatar asked Aug 24 '26 11:08

NibblyPig


1 Answers

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;
like image 178
Luaan Avatar answered Aug 27 '26 00:08

Luaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!