C# : System.Net.WebException: The underlying connection was closed

后端 未结 2 537
南方客
南方客 2021-01-22 12:04

I have the following code :

String url = // a valid url
String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it
byte[] bytes =         


        
2条回答
  •  长发绾君心
    2021-01-22 12:33

    Don't close the stream before reading from it. This should work:

    String url = // a valid url
    String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Credentials = new NetworkCredential("DEFAULT\\Admin", "Admin"); 
    request.ContentType = "application/xml";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    request.KeepAlive = false;
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(bytes, 0, bytes.Length);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(responseStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
    }
    

提交回复
热议问题