user797717
user797717

Reputation: 788

How to properly disconnect from FTP server with FtpWebRequest

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?

Upvotes: 9

Views: 18740

Answers (2)

Nattrass
Nattrass

Reputation: 1313

Have you tried wrapping your response in a using statement?

using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(responseStream))
                {
                    string responseString = streamReader.ReadToEnd();

                    Byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    memoryStream = new MemoryStream(buffer);
                }

                responseStream.Close();
            }
            response.Close();
        }

Upvotes: 1

Jamleck
Jamleck

Reputation: 1037

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;

Upvotes: 14

Related Questions