【问题标题】:FTP Check if file exist when Uploading and if it does rename it in C#FTP 在上传时检查文件是否存在以及是否在 C# 中重命名
【发布时间】:2011-03-15 15:05:48
【问题描述】:

我有一个关于使用 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)
    {

    }
}

【问题讨论】:

  • 您遇到了哪些问题?看起来您已经准备好大部分代码了。

标签: c# .net ftp


【解决方案1】:

我只是把它放在一起并不是特别优雅,但我想这几乎是你需要的吗?

您只想继续尝试您的请求,直到收到“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;
        }
    }

编辑:更新后,这将适用于任何类型的网络请求,并且更精简。

【讨论】:

    【解决方案2】:

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

    您也可以使用@987654321@ file 命令检查文件是否已经存在(用于检索文件的时间戳)。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        request.Method = WebRequestMethods.Ftp.GetFileSize;
        

        并没有真正起作用。有时它给出了异常,有时它没有。对于同一个文件!不知道为什么。

        我按照泰德所说的(谢谢,顺便说一句)把它改成

        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
        

        它现在似乎可以工作了。

        【讨论】:

        • 如果您有新问题,请点击 按钮提出问题。如果有助于提供上下文,请包含指向此问题的链接。
        • 我没有任何问题。我只是指出他编写的代码与我正在使用的代码相同,但对我而言,由于“GetFileSize”,它并没有真正起作用。我通过检查“文件的时间戳”解决了这个问题,现在它似乎可以工作了。我在这里写它是因为我从 Tedd 那里得到了这个想法,并认为也许其他人可以从中受益。哈哈
        猜你喜欢
        • 2012-11-07
        • 2013-06-23
        • 1970-01-01
        • 2012-04-18
        • 2013-08-14
        • 2013-12-02
        • 2013-05-19
        • 1970-01-01
        • 2018-04-02
        相关资源
        最近更新 更多