是否有一种简单,快速的方法来检查FTP连接(包括主机,端口,用户名和密码)是否有效且有效?我正在使用C#。谢谢。
答案 0 :(得分:16)
尝试这样的事情:
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://ftp.google.com");
requestDir.Credentials = new NetworkCredential("username", "password");
try
{
WebResponse response = requestDir.GetResponse();
//set your flag
}
catch
{
}
答案 1 :(得分:5)
/ * HOLA Este es el metodo que utilizo si conoces uno mejor hasmelo saber Ubirajara 100%Mexicano isc.erthal@gmail.com * /
private bool isValidConnection(string url, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(user, password);
request.GetResponse();
}
catch(WebException ex)
{
return false;
}
return true;
}
答案 2 :(得分:3)
您可以尝试使用
System.Net.FtpWebRequest
然后只需检查GetResponseStream
方法。
类似
System.Net.FtpWebRequest myFTP = new System.Net.FtpWebRequest
//Add your credentials and ports
try
{
myFTP.GetResponseStream();
//set some flags
}
catch ex
{
//handle it when it is not working
}
答案 3 :(得分:1)
使用System.Net.FtpWebRequest或System.Net.WebRequestMethods.Ftp使用您的登录凭据测试您的连接。如果FTP请求因任何原因失败,将返回相应的错误消息,指出问题是什么(身份验证,无法连接等等)
答案 4 :(得分:0)
这可能有用。
public async Task<bool> ConnectAsync(string host, string user, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host);
request.Credentials = new NetworkCredential(user, password);
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; // useful when only to check the connection.
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) await _ftpRequest.GetResponseAsync();
return true;
}
catch (Exception)
{
return false;
}
}
答案 5 :(得分:-2)
这是从msdn站点显示来自服务器的文件
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}