For the past few weeks, an FTP upload has been failing, rather religiously, with the following .Net error:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
For the FTP upload, I was using the .Net FtpWebRequest
class, in a rather simple code snippet:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(config.Uri); request.UsePassive = config.UsePassive; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(config.UserName, config.Password);
The FTP connection was dropping, but why? The transfer file was rather large (over 50MB), but reading the MSDN documentation for the FtpWebRequest.Timeout property, it was pretty clear that the .Net Framework wasn’t timing out, because:
FtpWebRequest.Timeout Property
Type: System.Int32
An Int32 value that contains the number of milliseconds to wait before a request times out. The default value is Infinite.
I tried active and passive connections; both failed. I checked the firewall; nothing unusual. I tried other external servers; they all failed. What gives?
Finally, exasperated, I tried forcing the timeout:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(config.Uri); request.UsePassive = config.UsePassive; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(config.UserName, config.Password); request.Timeout = -1;
Viola! The FTP upload did not fail! Stepping through the code, I found that, contrary to the documentation, the default value for FtpWebReqeust.Timeout is not infinite:
That is right, my friends: contrary to what you read in the documentation, the default value is 100,000 milliseconds, or about 1 minute, 40 seconds.
Lessons learned:
- Don’t believe everything you read.
- Trust, but verify.
- Infinite is not infinite when it is not infinite.
Ali says:
Thanks buddy! This helped me too. I was getting the same error.
Dave says:
5 years later and I got bit by this same problem. Same scenario. Thanks.