检测有效的FTP连接

时间:2015-06-18 22:14:41

标签: c# ftpwebrequest

我看到了线程     How to check FTP connection? 并尝试了一些建议。这是我现在拥有的:

    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");
        }
    }

如果用户名/密码无效,则记录的最后一件事是“刚进入TRY块”。代码以某种方式默默地出错并且永远不会记录“坏”。如果凭据有效,则继续执行并记录“GOOD”。

我想这给了我一个关于登录是否完全成功的布尔值。但有没有办法区分凭据是否坏或者是否只是没有响应的FTP服务器?

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该使用从FTPWebRequest获得的响应中的状态代码。

您可以看到完整列表here

如果您的实施

   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");
    }

以下是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;
    }