【问题标题】:How to properly disconnect from FTP server with FtpWebRequest如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接
【发布时间】:2014-07-25 20:49:11
【问题描述】:

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

问题是几个小时后,我从 FTP 服务器收到一条错误消息(已达到 -421 会话限制..)。当我使用 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;

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

【问题讨论】:

    标签: c# ftp ftp-client ftpwebrequest


    【解决方案1】:

    尝试将FtpWebRequest.KeepAlive 属性设置为false。如果KeepAlive设置为false,那么当请求完成时,到服务器的控制连接将被关闭。

    ftpWebRequest.KeepAlive = false;
    

    【讨论】:

    • 将 KeepAlive 设置为 false 时,在响应上调用 Close 方法时连接将关闭。因此,请务必在之后始终调用 ftpWebResponse.Close()!
    【解决方案2】:

    您是否尝试将响应包装在 using 语句中?

    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();
            }
    

    【讨论】:

    • AFAIK FtpWebResponse 没有实现 IDisposable 接口。我会尝试添加一个 finally 块并关闭其中的流。
    • 你确定吗,MSDN 似乎是这么说的。 msdn.microsoft.com/en-us/library/…
    • 是的,你是对的。我试图包装 FtpWebRequest 而不是 FtpWebResponse。
    • 我刚试过这个,但 Close() 调用都没有达到预期的效果;我的 FTP 服务器日志仅在我的应用程序终止时才显示连接关闭。 Jamleck 的回答虽然有效。
    猜你喜欢
    • 2012-06-10
    • 2020-10-14
    • 2012-11-29
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多