在C#(.NET 4.6)中关闭保持活动状态的FTP或FTPS连接的最佳方法? [英] Best method to close a keep-alive FTP or FTPS connection in C# (.NET 4.6)?

查看:194
本文介绍了在C#(.NET 4.6)中关闭保持活动状态的FTP或FTPS连接的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#(.NET 4.6)中,我使用保持活动的FTPS连接在这样的循环中下载几个文件:

In C# (.NET 4.6) I am using a keep-alive FTPS connection to download a couple of files in a loop like this:

foreach (string filename in filenames)
{
  string requestUriString = GetFtpUriString(myDir) + "/" + filename;
  FtpWebRequest request = (FtpWebRequest)WebRequest.Create(requestUriString);
  request.Method = WebRequestMethods.Ftp.DownloadFile;
  request.Credentials = new NetworkCredential(myFtpsUsername, myFtpsPassword);
  request.EnableSsl = true;
  request.ConnectionGroupName = myConnectionGroupName;
  request.KeepAlive = true;

  ... do something ...
}

循环完成后,我想关闭连接.我找不到直接的方法来完成此任务.我想到的是以下解决方法,它向FTP服务器发出了另一个低占用空间的请求,这次将KeepAlive标志设置为false:

After the loop is done, I want to close the connection. I could not find a direct way to accomplish this. What I came up with is the following work-around, which makes another low-footprint request to the FTP server, this time with the KeepAlive flag set to false:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetFtpUriString(myDir));
request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
request.Credentials = new NetworkCredential(myFtpsUsername, myFtpsPassword);
request.EnableSsl = true;
request.ConnectionGroupName = myConnectionGroupName;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();

我现在想知道是否存在另一种更简单,更优雅,更直接的方法来关闭特定连接组的打开的FTP连接.

I am wondering now whether there exists another, simpler, more elegant and direct way to close an open FTP connection for a specific connection group.

推荐答案

FtpWebRequest实例的连接池没有任何公共接口.

The connection pool of FtpWebRequest instances does not have any public interface.

但是有一个简单的解决方案,只需在循环的最后一轮将KeepAlive设置为false.

But there's an easy solution, just set the KeepAlive to false in the last round of the loop.

这篇关于在C#(.NET 4.6)中关闭保持活动状态的FTP或FTPS连接的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆