问题
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