FTP Check if file exists at boot and if it renames it in C #

I have a question about uploading to FTP from C #.

What I want to do is if the file exists, then I want to add either Copy or 1 after the file name so that it does not replace the file. Any ideas?

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)
    {

    }
}
+3
source share
4 answers

It is not particularly elegant because I just threw it together, but I think this is pretty much what you need?

You just want to continue your requests until you get "ActionNotTakenFileUnavailable", so you know your file name is good, and then just load 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 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 a little thinner.

+5
source

FTP (send-receive), . , dir : dos unix

MDTM file, , ( ).

+2

. dir , #, , .

0

- . :

request.Method = WebRequestMethods.Ftp.GetFileSize;

. , . ! , .

, (, ),

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

.

0

All Articles