簡體   English   中英

FTP上傳時檢查文件是否存在,是否在C#中重命名

[英]FTP Check if file exist when Uploading and if it does rename it in C#

我有一個關於使用C#上傳到FTP的問題。

我想要做的是,如果文件存在,那么我想添加像文件名后面的復制或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)
    {

    }
}

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

你只是想繼續嘗試你的請求,直到你得到一個“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請求,並且稍微有點苗條。

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

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

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

request.Method = WebRequestMethods.Ftp.GetFileSize;

真的沒有用。 有時候它會有例外但它沒有。 而對於同一個文件! 不知道為什么。

我改變它,因為Tedd說(謝謝,順便說一下)

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

它現在似乎工作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM