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

How to properly disconnect from FTP server with FtpWebRequest(如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接)
本文介绍了如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

当我尝试通过命令行或 FileZilla 执行相同操作时,连接已正确关闭.

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?

推荐答案

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

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;

这篇关于如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)