Stream无法读取 - 没有任何处理,为什么这不起作用?

时间:2011-03-21 23:48:25

标签: c# .net

我有以下代码:

 // 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();
 }

当流程点击using(.....)语句时,我得到以下异常:

  

Stream无法读取

我想将整个请求流读入字符串,没有关闭,所以代码应该有效吗?

2 个答案:

答案 0 :(得分:3)

您写入请求流并从响应流中读取。

    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 );

答案 1 :(得分:0)

流不可读,因为它打算写入。请参阅此链接以获取一个简单示例:

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