How to move/rename file using WinSCP .NET Assembly when target file exist already?

Suravi picture Suravi · Jan 23, 2014 · Viewed 7.1k times · Source

I'm developing SFTP file transferring project using WinSCP .NET Assembly (C#).

I want to move files in server. Here is the code:

session.MoveFile(server.RemoteDownloadPath + fileInfo.Name, server.DoneFilePath);
Console.WriteLine("Move File {0} to {1}", fileInfo.Name, server.DoneFilePath);

If current moving file exist in target path it does not move. So I want to rename file and move it.

Is there any way to do that?

Answer

Martin Prikryl picture Martin Prikryl · Jan 23, 2014

If you are asking, if WinSCP can do this automatically for you, the answer is "no".

You need to explicitly check target file existence and rename it before you move the file.

Note that rename and move is the same operation from WinSCP .NET Assembly API perspective. So you use the Session.MoveFile method for both.

From your question, it's not clear if the server.DoneFilePath is a path to the target directory (ending with slash /) or a path to the target file (ending with file name). Assuming it is a path to the target directory only:

string doneFile = server.DoneFilePath + fileInfo.Name;
if (session.FileExists(doneFile))
{
    session.MoveFile(doneFile, doneFile  + ".bak");
}

// carry on with your move code:
session.MoveFile(server.RemoteDownloadPath + fileInfo.Name, server.DoneFilePath);