How to use Atomic POSIX rename in SFTP

In SFTP protocol, if the target file already exists then rename operation fails. Hence it creates a problem for Unix-like filesystems based on POSIX standard, which specifies that the target file is deleted if it already exists.

Because of this, Unix-based SFTP servers can't implement SFTP rename command using Unix's POSIX-like rename function, but have to work around the difference by creating a hard link using the new name, followed by removing the original name. Unfortunately, this approach fails on filesystems that don't support hard links (such as FAT).

Another problem with this approach is that SFTP rename is not atomic because it consists of two operations, unlike POSIX rename function.

To solve these issues, a 'posix-rename' extension was introduced in OpenSSH 4.8 and has been implemented by other SFTP servers as well.

With the Ultimate SFTP you can use this extension (when available), just set Sftp object's Config.EnablePosixRename property to true to indicate to use POSIX rename, if available, instead of standard SFTP rename.

The following examples take advantage of that property to enable POSIX rename:

Rename a single file or directory

The Rename method helps you rename/move a single file or directory. The first parameter is the source remote SFTP item, and the second parameter is the target item.

// Use 'Posix rename' when available
client.Config.EnablePosixRename = true;

// Rename a remote file
client.Rename("/MyData/a.txt", "/MyData/b.txt");
' Use 'Posix rename' when available
client.Config.EnablePosixRename = True

' Rename a remote file
client.Rename("/MyData/a.txt", "/MyData/b.txt")

Move multiple files and directories

Our API also has support for renaming/moving multiple items. You can monitor the operation progress using the Progress event.

TransferOptions opt = new TransferOptions(
        true, // Build directory structure. 
        true, // Recursive. 
        OptionValue.Yes, // Create empty directories.   
        (SearchCondition)null, //  
 opt.DeleteEmptyDirectories = true; // Remove empty directories.             
 // Move all .cs and .vb files to a new folder. 
 client.Move("/myfolder2/*.cs,*.vb", "/my new folder", opt);

45-Day Money Back Guarantee

We will refund your full money in 45 days
if you are not satisfied with our products

Buy Now

Dont miss out Get update on new articles and other opportunities