GurdeepS
GurdeepS

Reputation: 67273

Stream was not readable - nothing is disposed of, why does this not work?

I have the following code:

 // Create POST data and convert it to a byte array.
 string postData = "name=t&description=tt";
 byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 // Set the ContentType property of the WebRequest.
 request.ContentType = "application/x-www-form-urlencoded";
 // Set the ContentLength property of the WebRequest.
 request.ContentLength = byteArray.Length;
 // Get the request stream.
 using (StreamReader reader = new StreamReader(request.GetRequestStream()))
 {
     string s = reader.ReadToEnd();
 }

When the flow hits the using (..... ) statement, I get the following exception:

Stream was not readable

I want to read the entire request stream into a string, nothing is closed, so the code should work?

Upvotes: 2

Views: 10102

Answers (2)

MusiGenesis
MusiGenesis

Reputation: 75386

The stream is not readable, because it's intended to be written to. See this link for a simple example:

http://www.netomatix.com/httppostdata.aspx

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532665

You write to the Request stream and read from the Response stream.

    string postData = "name=t&description=tt";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.

    var stream = request.GetRequestStream();
    stream.Write( byteArray, 0, byteArray.Length );

Upvotes: 4

Related Questions