CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2009
    Posts
    144

    The underlying connection was closed: The connection was closed unexpectedly

    Hello , i get this error message : The underlying connection was closed: The connection was closed unexpectedly at this code


    Code:
     try
                    {
    
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://x.x.x.x:4042/admin.cgi?pass=test&mode=viewxml");
    
                        req.ContentType = "text/xml;charset=\"utf-8\"";
                        req.Accept = "text/xml";
                        req.Method = "HEAD";
    
                        WebResponse resp = req.GetResponse();
                        
                        StreamReader r = new StreamReader(resp.GetResponseStream());
    
                        richTextBox1.AppendText(r.ReadToEnd()+"\n");
    
    
                    }
                    catch (System.Net.WebException webe)
                    {
                        richTextBox1.AppendText(webe.ToString() + "\n");
                        richTextBox1.AppendText(webe.Response.ToString() + "\n");
                        richTextBox1.AppendText(webe.Message.ToString());
    
                    }



    can you help me ? thanks

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: The underlying connection was closed: The connection was closed unexpectedly

    By default the web request keeps an open connection which expires after a while and causes the exception. The fix is to turn the KeepAlive off.

    Code:
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(...);
    req.KeepAlive = false;
    
    ...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured