【问题标题】:Best method to close a keep-alive FTP or FTPS connection in C# (.NET 4.6)?在 C# (.NET 4.6) 中关闭保持活动的 FTP 或 FTPS 连接的最佳方法?
【发布时间】:2016-08-09 15:54:08
【问题描述】:

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

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

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 连接。

【问题讨论】:

  • 你解决了吗?

标签: c# ftp keep-alive ftps .net-4.6


【解决方案1】:

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


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

【讨论】:

  • 我自己考虑过这个“解决方案”。在List 或类似集合的情况下,它可以,但对于使用任意IEnumerable 的一般“解决方案”,我认为它不如我的“解决方案”,因为它需要枚举中的项目数事先知道。换句话说:如果我不想失去对循环集合的惰性求值的好处,我需要坚持我原来的“解决方案”。
猜你喜欢
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2018-09-30
  • 2010-10-22
  • 2010-09-29
  • 1970-01-01
相关资源
最近更新 更多