Search code examples
c#asp.net-4.0system.net.webexception

Error when trying Stream.Write several times in C# net 4.0


    string CRLF = "\r\n";
    string boundary = "--" + DateTime.Now.Ticks.ToString("x") + "--";
    byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes(CRLF + boundary + CRLF);
    string content_Type = "multipart/form; boundary=" + boundary +"; charset=UTF-8";

    request.Headers.Add("Authorization", "Bearer " + accessToken);  // 헤더 설정
    request.Headers.Add("consumerKey", consumerKey);
    request.Method = "POST";
    request.Date = DateTime.Now;
    request.ContentType = content_Type;

    Stream rs = request.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\""+CRLF+CRLF+"{1}";
    foreach (string key in param.Keys)
    {
        rs.Write(boundaryBytes, 0, boundaryBytes.Length);
        string formitem = string.Format(formdataTemplate, key, param[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
        rs.Close();
    }
    rs.Write(boundaryBytes, 0, boundaryBytes.Length);

I get an error here.

    rs.Write(boundaryBytes, 0, boundaryBytes.Length);

Error details

     System.Net.WebException was unhandled by user code
     HResult=-2146233079
     Message=The request has been aborted.The connection was closed unexpectedly.
     Source=System
      StackTrace:
     위치: System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 
     size, AsyncCallback callback, Object state)
     위치: System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size)

   위치: Telerik.Web.UI.RadButton.OnClick(ButtonClickEventArgs e)
   위치: Telerik.Web.UI.RadButton.RaisePostBackEvent(String eventArgument)
   위치: Telerik.Web.UI.RadButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   위치: System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   위치: System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   위치: System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean 
  includeStagesAfterAsyncPoint)
  InnerException: 

What I don't understand is that there was no error 10 days ago.

And when rs.Write three times, an error occurs. Just pass through the second.


Solution

  • Try moving the

     rs.Close();
    

    e.g.,

    foreach (string key in param.Keys)
    {
        rs.Write(boundaryBytes, 0, boundaryBytes.Length);
        string formitem = string.Format(formdataTemplate, key, param[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
    }
    rs.Write(boundaryBytes, 0, boundaryBytes.Length);
    rs.Close();