Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close/destruct an FtpWebRequest

Tags:

c#

.net

object

ftp

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

like image 969
Walter Fabio Simoni Avatar asked Jul 10 '13 12:07

Walter Fabio Simoni


2 Answers

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.

like image 65
sundog Avatar answered Nov 20 '22 09:11

sundog


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.

like image 9
Raidri Avatar answered Nov 20 '22 09:11

Raidri