c# - 如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接

标签 c# ftp ftp-client ftpwebrequest

我创建了一个 ftp 客户端,它在一天中多次连接以从 FTP 服务器检索日志文件。

问题是,几个小时后我从 FTP 服务器收到一条错误消息(达到 -421 session 限制..)。当我使用 netstat 检查连接时,我可以看到几个与服务器的“已建立”连接,即使我已经“关闭”了连接。

当我尝试通过命令行或 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;

如何正确关闭/断开连接?我是不是忘记了什么?

最佳答案

尝试设置 FtpWebRequest.KeepAlive属性为假。如果 KeepAlive 设置为 false,则在请求完成时将关闭与服务器的控制连接。

ftpWebRequest.KeepAlive = false;

关于c# - 如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24050381/

相关文章:

c# - 您如何在运行时判断 IEnumerable<T> 是否已延迟?

c# - 使用 Func<> 类型来分配/更改变量

java - 如何手动查找android文件的文件路径?

java - org.apache.commons.net.ftp 使用不同的端口

java - Ftp 客户端无法使用 IPV6 传输文件

C# UWP XAML 动画

c# - 为什么任何长度的 key 都适用于 RijndaelManaged?

android - 通过android在特定路径下上传文件

java - Apache ftpserver 上传通知

php - 在php中以编程方式将文件从一台服务器复制到另一台服务器