开发者

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

I have a question about Uploading to a FTP with C#.

What I want to do is if the file exists then I want to add like Copy or a 1 after the filename so it doesn't replace the file. Any Ideas?

var request = (FtpWebRequest)WebRequest.Create(""+destination+file);
reque开发者_如何学Pythonst.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)
    {

    }
}


It's not particularly elegant as I just threw it together, but I guess this is pretty much what you need?

You just want to keep trying your requests until you get a "ActionNotTakenFileUnavailable", so you know your filename is good, then just upload it.

        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;
        }
    }

Edit: Updated so this will work for any type of web request and is a little slimmer.


Since FTP control protocol is slow in nature (send-receive) I suggest first pulling directory content and checking against it before uploading the file. Note that dir can return two different standards: dos and unix

Alternatively you can use the MDTM file command to check if file already exist (used to retrieve timestamp of a file).


There is no shortcut. You need to dir the target directory then use # to determine which name you want to use.


I am working on something similar. My problem was that:

request.Method = WebRequestMethods.Ftp.GetFileSize;

was not really working. Sometimes it gave exception sometimes it didn't. And for the same file! Have no idea why.

I change it as Tedd said (thank you, btw) to

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

and it seems to work now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜