Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
user797717 Avatar asked Jun 05 '14 01:06

user797717


2 Answers

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;
like image 106
Jamleck Avatar answered Sep 30 '22 18:09

Jamleck


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();
        }
like image 31
Nattrass Avatar answered Sep 30 '22 18:09

Nattrass