Detecting valid FTP connection

3.5k Views Asked by At

I saw the thread at How to check FTP connection? and tried some of the suggestions. Here's what I currently have:

    private void IsFtpLoginSuccessful(FtpClient ftpClient, string ftpFolder, string ftpUsername, string ftpPassword)
    {
        FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(ftpFolder);
        requestDir.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
        try
        {
            Log(LogLevel.Debug, "Just entered TRY block");
            requestDir.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            WebResponse response = requestDir.GetResponse();
            Log(LogLevel.Debug, "GOOD");
        }
        catch (Exception ex)
        {
            Log(LogLevel.Debug, "BAD");
        }
    }

If the username / password are invalid, the last thing that's logged is "Just entered TRY block". The code somehow silently errors-out and never logs "BAD". If the credentials are valid, it continues execution and logs "GOOD".

I suppose that gives me a Boolean as to whether the log-in was completely successful. But is there a way to distinguish whether the credentials are bad or if it's the FTP server that's just not responding?

Thank you!

1

There are 1 best solutions below

0
On BEST ANSWER

You should be using the status codes in the response you get from the FTPWebRequest.

You can see a full list here

In case of your implementation

   private void IsFtpLoginSuccessful(FtpClient ftpClient, string ftpFolder, string ftpUsername, string ftpPassword)
    {
        FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(ftpFolder);
        requestDir.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

        Log(LogLevel.Debug, "Just entered TRY block");
        requestDir.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();

        if(response.StatusDescription != FtpStatusCode.CommandOK || response.StatusDescription != FtpStatusCode.FileActionOK)
            Log(LogLevel.Debug, "BAD");
    }

Here's the sample code on MSDN.

    public static bool MakeDirectoryOnServer (Uri serverUri)
    {
        // The serverUri should start with the ftp:// scheme. 
        if (serverUri.Scheme != Uri.UriSchemeFtp)
        {
            return false;
        }

        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create (serverUri);
        request.KeepAlive = true;
        request.Method = WebRequestMethods.Ftp.MakeDirectory;

        //Getting the status description
        FtpWebResponse response = (FtpWebResponse)request.GetResponse ();
        Console.WriteLine ("Status: {0}", response.StatusDescription);
        return true;
    }