Using IRemoteFileSystem to work with both SFTP and FTP without writing duplicate code.

The interface IRemoteFileSystem is designed to help developers write single fragment of code that can work with both SFTP and FTP. It has some common method for connecting, authenticating and disconnecting. The following example demonstrates how to use the interface to start a connection, authenticate, upload, download, and end the connection.

void SFTPandFTPConnection(IRemoteFileSystem client, string host, int port, string username, string password)
 {
 client.Connect(host, port);
 client.Authenticate(username, password);
 FileSystem system = client as FileSystem;
 
 // Delete files
 client.DeleteFiles("*.tmp");
 
 // Create a new directory
 client.CreateDirectory("my dir");
 
 // Download files from the root directory.
 TransferOptions opt = new TransferOptions();
 opt.Recursive = true;
 FileSystem.TransferFiles(system, "/", (IFileInfo[])null, DiskFileSystem.Default, @"C:\temp", opt);
 
 // Upload files from C:\test to the root directory
 FileSystem.TransferFiles(DiskFileSystem.Default, @"C:\Test", (IFileInfo[])null, system, "/", opt);
 client.Disconnect();
 }

Workaround for 'Invalid Key Size' error in the version 3.5

You may experience 'Invalid Key Size' error when connecting to your server. This bug is addressed in the ComponentSoft version (2011.2 - v5.0) that we are working on. To go through this error in the current version 2011.1 - v3.5, you can set AllowedMacAlgorithms and/or AllowedHostKeyAlgorithms. The following examples demonstrate how to set them:

Setting AllowedMacAlgorithms

Sftp s = new Sftp(); s.AllowedMacAlgorithms = SshMacAlgorithm.MD5;

Setting AllowedHostKeyAlgorithms

Sftp s = new Sftp(); s.AllowedHostKeyAlgorithms = SshHostKeyAlgorithm.Rsa;

If you still experience the error, please send us your log file and we will investigate it.

How to verify SFTP Server's Fingerprint

Some customers have asked us to post an example of how to display and verify the server's fingerprint. It's quite simple if you know that the Sftp class has an event named HostKeyVerifying. You can simply handle this event with the following code:

C#:

client.HostKeyVerifying += client_HostKeyVerifying;


VB.NET

AddHandler client.HostKeyVerifying, AddressOf client_HostKeyVerifying

In the event handler method named client_HostKeyVerifying, you can display the fingerprint of the server to your Console window or Win Form and let user confirm whether he or she accepts that fingerprint. The following code demonstrates how we do that in a Console application:

C#:

Console.WriteLine("Server's fingerprint: " + e.HostKey);
Console.WriteLine("Accept this fingerprint? (y/n): ");
e.Accept = Console.ReadLine().ToLower() == "y";

VB.NET

Console.WriteLine("Server's fingerprint: " & e.HostKey)
Console.WriteLine("Accept this fingerprint? (y/n): ")
e.Accept = Console.ReadLine().ToLower() = "y"

Using the SFTP component to connect to an SCP server

To authenticate to an SCP server, you can simply perform the following steps: Connect to the SFTP/SCP server, verify the server's fingerprint, use your user name and password to login, do your work like uploading file, downloading file, etc. After completing your work, call the Disconnect method to close the SCP session. The example below shows how to authenticate to an SCP server.

// Create a new instance.
Scp client = new Scp();
try
{
   // Connect to the SCP server.
   client.Connect("localhost");
   // Authenticate.
   client.Authenticate("test", "test");
   // ...
   // Disconnect.
   client.Disconnect();
}
catch (ScpException exc)
{
   Console.WriteLine("An error occurred: Code: {0}, Message: {1}", exc.Status, exc.Message);
   if (client.State != RemoteFileSystemState.Disconnected)
       client.Disconnect();
}

' Create a new instance.
Dim client As New Scp()
Try
    ' Connect to the SCP server.
    client.Connect("localhost")
    ' Authenticate.
    client.Authenticate("test", "test")
    ' ...
    ' Disconnect.
    client.Disconnect()
Catch exc As ScpException
    Console.WriteLine("An error occurred: Code: {0}, Message: {1}", exc.Status, exc.Message)
    If client.State <> RemoteFileSystemState.Disconnected Then
        client.Disconnect()
    End If
End Try

Getting absolute path of an object on an SFTP server

Ultimate Sftp class exposes the GetAbsolutePath method which is used to retrieve absolute path of a remote path. To use this method, simply pass the remote relative path you wish to process to the only one parameter of the method and it will return the absolute path.

The following steps guide you on how to use this method.

C#:

// Create a new instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Retrieve the absolute path of the path "testdir/test.dat".
string relativePath = "testdir/test.dat";
string absolutePath = client.GetAbsolutePath(relativePath);
Console.WriteLine("Absolute path of '{0}' is '{1}'", relativePath, absolutePath);
// ...
// Disconnect.
client.Disconnect();

VB.NET:

' Create a new instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Retrieve the absolute path of the path "testdir/test.dat".
Dim relativePath As String = "testdir/test.dat"
Dim absolutePath As String = client.GetAbsolutePath(relativePath)
Console.WriteLine("Absolute path of '{0}' is '{1}'", relativePath, absolutePath)
' ...
' Disconnect.
client.Disconnect()

Using Ultimate FTP & SFTP Libraries to Transfer Files Between FTP & SFTP Servers

To upload a file from other file system to an FTP file system (in Ultimate FTP Library), simply use the CopyFrom methods.

The following example demonstrates how to connect to FTP and SFTP servers, and use the CopyFrom method to directly copy a file from the SFTP file system to the FTP file system. If you need to upload files and directories within a ZIP file to the SFTP server, see the topic Uploading files and directories within a ZIP file to an FTP server.

Remember to add using directives to your code to create aliases for existing namespaces and avoid having to type the fully qualified type names. The namespaces are ComponentSoft.Net and ComponentSoft.IO.

The following example demonstrates copying files from an SFTP server to an FTP server without creating temporary files on the local PC.

Before using the component, please add references to assemblies in the picture below:

ATP References

Using Ultimate SFTP and FTP components to transfer a file

C#  
// Connect to an FTP file system.
Ftp ftpsys = new Ftp();
ftpsys.Connect(
"192.168.126.128", 21);
ftpsys.Authenticate(
"test", "test");
// Connect to an SFTP file system.
Sftp sftp = new Sftp();
sftp.Connect(
"192.168.126.128", 2222);
sftp.Authenticate(
"test", "test");
// Copy 'blog.txt' file from the SFTP file system to the FTP file system.
ftpsys.CopyFrom(sftp, "blog.txt", "my blog on FTP file system.txt");
ftpsys.Disconnect();
sftp.Disconnect();

VB.NET  
' Connect to an FTP file system.
Dim ftpsys As New Ftp()
ftpsys.Connect("192.168.126.128", 21)
ftpsys.Authenticate("test", "test")
' Connect to an SFTP file system.
Dim sftp As New Sftp()
sftp.Connect("192.168.126.128", 2222)
sftp.Authenticate("test", "test")
' Copy 'blog.txt' file from the SFTP file system to the FTP file system.
ftpsys.CopyFrom(sftp, "blog.txt", "my blog on FTP file system.txt")
ftpsys.Disconnect()
sftp.Disconnect()

The CopyFrom method of the FileSystem class queries information for the source file, creates a new file for writing on the destination file system and initiate the data transfer between the source file system and the destination file system.

If you need to upload selected files to an SFTP server, please see Uploading selected files using Ultimate SFTP topic.

The component can be downloaded at this web page. For moe information about the component, please see this post and this web page.

How to upload selected files and directories with UltimateSftp

Use the UploadFiles method to easily upload selected files and directories from the local disk to the SFTP server. You just need to provide local path, remote path, files and directories to upload and transfer options, ComponentSoft Ultimate SFTP component will do the rest of hard work for you. Other examples for FTP can also be found at FTP blog.

The following steps show you how to use the UploadFiles method to upload multiple files to the remote server.

C#



// Create a new instance.
 Sftp client = new Sftp();
 // Connect to the SFTP server.
 client.Connect("localhost");
 // Authenticate.
 client.Authenticate("test", "test");
 // ...
 // List of files and directories to upload.
 string[] files = new string[] { "myfile", "my dir", @"c:\my folder\my dir2" };
 // Upload selected files and subdirectories in local folder 'c:\my folder' to the remote dir '/temp'.
 client.UploadFiles(@"c:\my folder", files, "/temp", new TransferOptions());
 // ...
 // Disconnect.
 client.Disconnect();


VB.NET

' Create a new instance.
 Dim client As New Sftp()
 ' Connect to the SFTP server.
 client.Connect("localhost")
 ' Authenticate.
 client.Authenticate("test", "test")
 ' ...
 ' List of files and directories to upload.
 Dim files() As String = {"myfile", "my dir", "c:\my folder\my dir2"}
 ' Upload selected files and subdirectories in local folder 'c:\my folder' to the remote dir '/temp'.
 client.UploadFiles("c:\my folder", files, "/temp", New TransferOptions())
 ' ...
 ' Disconnect.
 client.Disconnect()