2011-08-26 71 views
0

我有一段代碼應該檢查遠程服務器上是否存在目錄。它在路徑上執行ListDirectory命令,如果存在,則需要響應,如果不存在,則會有異常。FTP ListDirectory命令返回狀態碼125

問題是該命令返回代碼125 DataAlreadyOpen,所以我的代碼將其解釋爲成功,應該失敗。

我可能完全誤解了FTP的工作原理。我每次都會創建一個新請求,所以我不明白連接是如何打開的。

哦,並且代碼與根目錄一起工作,如ftp://myIP/Folder1,但不適用於ftp://myIP/Folder1/Folder2。順便說一句,我正在使用IIS FTP服務器。

public static bool DirectoryExists(string path) 
{ 
    try 
    { 
     var request = (FtpWebRequest)WebRequest.Create(path); 
     request.Credentials = new NetworkCredential("foo", "bar"); 
     request.Method = WebRequestMethods.Ftp.ListDirectory; 
     request.KeepAlive = false; 

     using (var response = (FtpWebResponse)request.GetResponse()) 
      return true; 
    } 
    catch (Exception ex) 
    { 
     return false; 
    } 
} 

我如何可靠地檢查一個目錄是否存在?我發現的所有代碼示例都使用這種技術。

+0

是否使用'WebRequestMethods.Ftp.PrintWorkingDirectory'而不是'ListDirectory'工作? – V4Vendetta

+0

@ V4Vendetta查看naveen的回答。不同的迴應,但沒有做我想要的。 – Edgar

回答

1

我工作圍繞這一問題通過使用WebRequestMethods.Ftp.MakeDirectory命令時,我想檢查是否存在一個目錄。如果它不存在,就創建它,如果它存在,我會捕獲異常並繼續。

1

嘗試改變將request.method到

request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory; 
+0

然後響應代碼是'257 PathnameCreated',但該目錄在服務器上仍然不存在。 – Edgar