C#中上传文件时检查文件是否存在,如果存在则重命名:FTP检查和重命名文件

4

我有一个关于使用C#上传到FTP的问题。

我的目标是,如果文件已经存在,我希望在文件名后添加“Copy”或“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)
    {

    }
}

你在哪个部分遇到了困难?看起来你已经完成了大部分的代码。 - Justin
4个回答

6

我做的不是特别优雅,只是随便拼凑了一下,但我想这大概就是你需要的吧?

你只需不断尝试请求,直到收到“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请求,并更加精简。


2

由于FTP控制协议的速度较慢(发送-接收),我建议在上传文件之前先拉取目录内容并检查。请注意,dir可以返回两种不同的标准:dos和unix。

或者,您可以使用MDTM文件命令来检查文件是否已经存在(用于检索文件的时间戳)。


1

我正在做类似的事情。我的问题是:

request.Method = WebRequestMethods.Ftp.GetFileSize;

并没有真正地工作。有时会出现异常,有时则不会。而且是对于同一个文件!不知道为什么。

我按照 Tedd 的建议进行了更改(顺便说一下,谢谢),变成了

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

现在看起来它似乎可以工作了。


1
如果您有新的问题,请通过单击提问按钮来提出。如果它有助于提供上下文,请包含此问题的链接。 - Søren Debois
我没有任何问题。我只是指出他写的代码与我使用的相同,但对于我来说,它并没有正常工作,因为涉及到“GetFileSize”。我通过检查文件的时间戳来解决了这个问题,现在看起来已经可以正常工作了。我在这里写下来是因为我从Tedd那里得到了这个想法,可能其他人也会受益。哈哈 - Zsolt

0

没有捷径。您需要使用dir命令查看目标目录,然后使用#来确定要使用的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接