I would like to create a C# function in order to test a connection to an FTP Server.
Here is my function :
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://" + strHost.Trim());
requestDir.Credentials = new NetworkCredential(strUser, strPass);
requestDir.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
WebResponse response = requestDir.GetResponse();
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
My problem is very simple :
I I use a good host ( a good FTP Host), my function return "OK". If, after, i use a bad host, it return an exception
ERROR 421 : Service not available. Closing control connection.
If, atfer, it re-test with the good adresse, i have a new time this exception.
I need to close and re-open my application in order to solve this problem.
I try with :
KeepAlive = true / false and no changes.
Anyone could help me please ?
Thanks a lot,
Best regards,
Nixeus
As FtpWebResponse implements IDisposable interface, you also could use it like this:
using (FtpWebResponse ftpWebResponse = (FtpWebResponse)requestDir.GetResponse())
{
...
}
No need to explicitly call the close method.
You should use the FtpWebResponse
class and close it after getting you directory listing:
try
{
FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
string status = response.StatusDescription;
response.Close();
return status;
}
More Information in the MSDN
Note:
Multiple calls to GetResponse return the same response object; the request is not reissued.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With