Best method to close a keep-alive FTP or FTPS conn

2019-04-14 03:18发布

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条回答
地球回转人心会变
2楼-- · 2019-04-14 04:02

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.

查看更多
登录 后发表回答