我创建了一个在一天中连接多次以从FTP服务器检索日志文件的ftp客户端。如何使用FtpWebRequest正确断开与FTP服务器的连接
问题是,几个小时后,我收到来自FTP服务器的错误消息(达到-421会话限制..)。当我使用netstat检查连接时,即使我“关闭”了连接,仍可以看到几个与服务器的“ESTABLISHED”连接。
当我尝试在命令行或FileZilla中执行相同操作时,连接已正确关闭。
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;
如何正确关闭/断开连接?我忘记了什么吗?
AFAIK FtpWebResponse没有实现IDisposable接口。我会尝试添加一个finally块并关闭那里的流。 – user797717
你确定,MSDN似乎是这么说的。 http://msdn.microsoft.com/en-us/library/system.net.ftpwebresponse(v=vs.110).aspx – Nattrass
是的,你是对的。我试图包装FtpWebRequest而不是FtpWebResponse。 – user797717