Best method to close a keep-alive FTP or FTPS connection in C# (.NET 4.6)?

流过昼夜 提交于 2019-12-13 12:13:43

问题


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 ...
}

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

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.


回答1:


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


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



来源:https://stackoverflow.com/questions/38855392/best-method-to-close-a-keep-alive-ftp-or-ftps-connection-in-c-sharp-net-4-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!