How to properly disconnect from FTP server with FtpWebRequest

user797717 picture user797717 · Jun 5, 2014 · Viewed 14.2k times · Source

I've created a ftp client that connects several times during the day to retrieve log files from a FTP server.

The Problem is that after a few hours I am getting an error message from the FTP server (-421 session limit reached..). When I check the connections with netstat, I can see several 'ESTABLISHED' connections to the server even though I've "closed" the connection.

When I try to do the same over the command line or FileZilla, the connections are properly closed.

ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Resource Cleanup */

localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;

How can I close/disconnect the connection properly? Did I forget anything?

Answer

Jamleck picture Jamleck · Jun 5, 2014

Try and set the FtpWebRequest.KeepAlive property to false. If KeepAlive is set to false, then the control connection to the server will be closed when the request completes.

ftpWebRequest.KeepAlive = false;