2011-03-15 41 views
3

我有一個關於使用C#上傳到FTP的問題。FTP檢查上傳時是否存在文件,如果它在C#中重命名它

我想要做的是如果文件存在,那麼我想添加像複製或1後面的文件名,所以它不會替換文件。有任何想法嗎?

var request = (FtpWebRequest)WebRequest.Create(""+destination+file); 
request.Credentials = new NetworkCredential("", ""); 
request.Method = WebRequestMethods.Ftp.GetFileSize; 

try 
{ 
    FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
} 
catch (WebException ex) 
{ 
    FtpWebResponse response = (FtpWebResponse)ex.Response; 
    if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) 
    { 

    } 
} 
+0

你有什麼問題嗎?看起來你已經擁有了大部分的代碼。 – Justin 2011-03-15 15:06:47

回答

5

這不是特別優雅,我只是把它扔在一起,但我想這幾乎是你所需要的?

你只是想繼續嘗試你的請求,直到你得到一個「ActionNotTakenFileUnavailable」,所以你知道你的文件名是好的,然後上傳它。

 string destination = "ftp://something.com/"; 
     string file = "test.jpg"; 
     string extention = Path.GetExtension(file); 
     string fileName = file.Remove(file.Length - extention.Length); 
     string fileNameCopy = fileName; 
     int attempt = 1; 

     while (!CheckFileExists(GetRequest(destination + "//" + fileNameCopy + extention))) 
     { 
      fileNameCopy = fileName + " (" + attempt.ToString() + ")"; 
      attempt++; 
     } 

     // do your upload, we've got a name that's OK 
    } 

    private static FtpWebRequest GetRequest(string uriString) 
    { 
     var request = (FtpWebRequest)WebRequest.Create(uriString); 
     request.Credentials = new NetworkCredential("", ""); 
     request.Method = WebRequestMethods.Ftp.GetFileSize; 

     return request; 
    } 

    private static bool checkFileExists(WebRequest request) 
    { 
     try 
     { 
      request.GetResponse(); 
      return true; 
     } 
     catch 
     { 
      return false; 
     } 
    } 

編輯:已更新,所以這將適用於任何類型的Web請求,並且有點苗條。

0

沒有捷徑。您需要dir目標目錄,然後使用#來確定您要使用的名稱。

2

由於FTP控制協議本質上是緩慢的(發送 - 接收),我建議先上傳目錄內容並在上傳文件之前檢查它。請注意,目錄可以返回兩種不同的標準:dos和unix

或者,您可以使用MDTM file命令來檢查文件是否已經存在(用於檢索文件的時間戳)。

0

我正在做類似的事情。我的問題是:

request.Method = WebRequestMethods.Ftp.GetFileSize; 

是不是真的工作。有時候它有時並不例外。併爲同一個文件!不知道爲什麼。

我改變它爲Tedd說(謝謝你,順便說一句),以

request.Method = WebRequestMethods.Ftp.GetDateTimestamp; 

,似乎現在的工作。

+1

如果您有新的問題,請點擊[問問題](http://stackoverflow.com/questions/ask)按鈕。如果有助於提供上下文,請包含此問題的鏈接。 – 2014-04-03 07:40:15

+0

我沒有任何問題。我只是指出,他編寫的代碼與我使用的代碼相同,但對我來說,由於「GetFileSize」,它並不真正有效。我通過檢查'文件的時間戳'來解決它,它現在似乎工作。我在這裏寫了這篇文章是因爲我從特德得到了這個想法,並認爲也許其他人可以從中受益。大聲笑 – Zsolt 2014-04-03 08:13:12

相關問題