3

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.

d.k.
  • 61
  • 5

1 Answers1

0

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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • I considered this "solution" myself. In case of a `List` or similar collection it would be ok, but for a general "solution" using an arbitrary `IEnumerable` I consider it inferior to my "solution", because it would require the number of items in the enumeration to be known beforehand. In other words: If I do not want to loose the benefits of lazy evaluation for the loop's collection, I need to stick to my original "solution". – d.k. Aug 09 '16 at 17:31