检测到有效的 FTP 连接
本文关键字:FTP 连接 有效 检测 | 更新日期: 2023-09-27 17:56:57
我在 如何检查FTP连接?并尝试了一些建议。这是我目前拥有的:
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 块"。代码以某种方式静默出错,从不记录"BAD"。如果凭据有效,它将继续执行并记录"GOOD"。
我想这给了我一个关于登录是否完全成功的布尔值。但是有没有办法区分凭据是否错误,或者是否是FTP服务器没有响应?
谢谢!
您应该在从 FTPWebRequest 获得的响应中使用状态代码。
您可以在此处查看完整列表
在您的实施的情况下
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;
}