2010-07-13 145 views
6

是否有一種簡單而快速的方式來檢查FTP連接(包括主機,端口,用戶名和密碼)是否有效並正常工作?我正在使用C#。謝謝。如何檢查FTP連接?

+2

一定要接受一個合適的答案,這一個diplay文件。 – 2010-07-13 04:59:49

回答

5

你可以嘗試使用 System.Net.FtpWebRequest,然後只檢查GetResponseStream方法返回的FTP請求失敗。

因此,像

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

你的代碼是不會編譯的 – sarsnake 2012-09-22 00:44:45

12

嘗試這樣的事:

 FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create("ftp://ftp.google.com"); 
     requestDir.Credentials = new NetworkCredential("username", "password"); 
     try 
     { 
      WebResponse response = requestDir.GetResponse(); 
      //set your flag 
     } 
     catch 
     { 
     } 
+0

我已經實現了類似於你的解決方案anishMarokey的東西,但是這對於安全的ftp站點來說似乎失敗了。您對如何測試ftps連接有任何瞭解嗎?謝謝。 – 2011-09-29 14:42:03

+1

對於此代碼的工作,您還需要設置請求方法(即requestDir.Method = WebRequestMethods.Ftp.ListDirectoryDe​​tails)。 – laurie 2013-09-25 13:03:49

+0

@ChrisMitchell .NET尚不支持SFTP,但有像[SSH.NET](http://sshnet.codeplex.com/)這樣的庫,具有該功能 – laurie 2013-09-25 13:09:57

4

/* HOLA 埃斯特ES EL方法方法闕utilizo SI conoces UNO MEJOR hasmelo軍刀 Ubirajara 100%的墨西哥 ISC。 [email protected] */

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; 
     } 
+5

StackOverflow使用英語作爲其主要語言。 – 2015-12-20 04:26:35

-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","[email protected]"); 
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; 
}