title: Error using HttpWebRequest to upload files with PUT
body: <p>We've got a .NET 2.0 WinForms app that needs to upload files to an IIS6 Server via WebDav. From time to time we get complaints from a remote office that they get one of the following error messages</p>
  
  <ul>
  <li>The underlying connection was closed:
  an unexpected error occurred on send.</li>
  <li>The underlying connection was closed:
  an unexpected error occurred on
  receive.</li>
  </ul>
  
  <p>This only seems to occur with large files (~20Mb plus). I've tested it with a 40Mb file from my home computer and tried putting 'Sleep's in the loop to simulate a slow connection so I suspect that it's down to network issues at their end... but </p>
  
  <ol>
  <li>The IT at the remote office are no help</li>
  <li>I'd like to rule out the posibility my code is at fault.</li>
  </ol>
  
  <p>So - can anybody spot any misakes or suggest any workarounds that might 'bulletproof' the code against this problem. Thanks for any help. Chopped down version of code follows:</p>
  
  <pre><code>    public bool UploadFile(string localFile, string uploadUrl)
      {
          HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
  
          try
          {
              req.Method = "PUT";
              req.AllowWriteStreamBuffering = true;
              req.UseDefaultCredentials = Program.WebService.UseDefaultCredentials;
              req.Credentials = Program.WebService.Credentials;
              req.SendChunked = false;
              req.KeepAlive = true;
              Stream reqStream = req.GetRequestStream();
              FileStream rdr = new FileStream(localFile, FileMode.Open, FileAccess.Read);
              byte[] inData = new byte[4096];
              int bytesRead = rdr.Read(inData, 0, inData.Length);
  
              while (bytesRead &gt; 0)
              {
                  reqStream.Write(inData, 0, bytesRead);
                  bytesRead = rdr.Read(inData, 0, inData.Length);
              }
  
              reqStream.Close();
              rdr.Close();
  
              System.Net.HttpWebResponse response = (HttpWebResponse)req.GetResponse();
              if (response.StatusCode != HttpStatusCode.OK &amp;&amp; response.StatusCode!=HttpStatusCode.Created)
              {
                  MessageBox.Show("Couldn't upload file");
                  return false;
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.ToString());
              return false;
          }
          return true;
      }
  </code></pre>