This section illustrates how to connect to an SFTP server and set connection settings.
In order to use the Ftp and other classes, you have to add references to ComponentPro.Sftp.dll, ComponentPro.Common.dll, ComponentPro.Network.dll, and ComponentPro.FileSystem.dll assemblies to your project.
Sftp
class.Connect
methods.Disconnect
method to close the session when done.// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Set security settings.
client.Config.HostKeyAlgorithms = SecureShellHostKeyAlgorithm.RSA;
client.Config.KeyExchangeAlgorithms = SecureShellKeyExchangeAlgorithm.DiffieHellmanGroupExchangeSHA256;
// Enable compression
client.Config.EnableCompression = true;
// Connect to the server.
client.Connect(serverName);
// ...
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Set security settings.
client.Config.HostKeyAlgorithms = SecureShellHostKeyAlgorithm.RSA
client.Config.KeyExchangeAlgorithms = SecureShellKeyExchangeAlgorithm.DiffieHellmanGroupExchangeSHA256
' Enable compression
client.Config.EnableCompression = True
' Connect to the server.
client.Connect(serverName)
' ...
End Using
The Sftp.Config
property has several useful connection options like EnableCompression
, HostKeyAlgorithms
, MacAlgorithms
, etc. If needed, set those before connecting to a server.
Some of the useful information about the current SSH session such as server/user name, server fingerprint, negotiated algorithms or SFTP protocol version are available when the connection is established or the user is authenticated.
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Get connection information
Console.WriteLine("Server: {0}:{1}, Host key: {2}, Host key algorithm: {3}, Server Identification: {4}",
client.ServerName, client.ServerPort, client.HostKey,
client.Connection.Cipher.HostKeyAlgorithm, client.Connection.ServerIdentification);
// Authenticate the user
client.Authenticate(userName, password);
Console.WriteLine("Logged in as: {0}", client.UserName);
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Get connection information
Console.WriteLine("Server: {0}:{1}, Host key: {2}, Host key algorithm: {3}, Server Identification: {4}", client.ServerName, client.ServerPort, client.HostKey, client.Connection.Cipher.HostKeyAlgorithm, client.Connection.ServerIdentification)
' Authenticate the user
client.Authenticate(userName, password)
Console.WriteLine("Logged in as: {0}", client.UserName)
End Using
// Check session state
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
bool connected;
int nativeErrorCode;
// Get connection state.
client.GetConnectionState(out connected, out nativeErrorCode);
Console.WriteLine(connected ? "Connection is still alive" : "Connection closed. Error code: " + nativeErrorCode);
}
' Check session state
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
Dim connected As Boolean
Dim nativeErrorCode As Integer
' Get connection state.
client.GetConnectionState(connected, nativeErrorCode)
If connected Then
Console.WriteLine("Connection is still alive")
Else
Console.WriteLine("Connection closed. Error code: " & nativeErrorCode)
End If
End Using
To determine if a session is still alive, use GetConnectionState
method. The method sends a "ping" packet to the server to ensure the connection is still up and running.
When the ReconnectionMaxRetries
property is set to a value greater than 0, if an operation is interrupted due to a broken connection, the component automatically determines whether it should reconnect to the server.
If a file transfer is in progress, the component will automatically resume transfer when the connection is re-established.
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
// Retry 2 times before reporting error.
client.ReconnectionMaxRetries = 2;
// If any error occurs while doing this operation, the client will check if reconnection is required.
// It will retry 2 time before throwing error.
FileInfoCollection list = client.ListDirectory("/data");
// ...
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
' Retry 2 times before reporting error.
client.ReconnectionMaxRetries = 2
' If any error occurs while doing this operation, the client will check if reconnection is required.
' It will retry 2 time before throwing error.
Dim list As FileInfoCollection = client.ListDirectory("/data")
' ...
End Using
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
// Retry 2 times before reporting error.
client.ReconnectionMaxRetries = 2;
// If any error occurs while doing this operation, the client will check if reconnection is required.
// It will retry 2 time before throwing error.
FileInfoCollection list = client.ListDirectory("/data");
// ...
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
' Retry 2 times before reporting error.
client.ReconnectionMaxRetries = 2
' If any error occurs while doing this operation, the client will check if reconnection is required.
' It will retry 2 time before throwing error.
Dim list As FileInfoCollection = client.ListDirectory("/data")
' ...
End Using
The Ultimate SFTP component fully supports many proxy servers (often referred to as "proxies"). If you need to connect to your SFTP server through a proxy, simply create a new instance of the FtpProxy
class, set the appropriate properties of the WebProxyEx
object, and assign it to the Proxy
property of the Sftp
class, and the necessary proxy communication will take place.
Ultimate SFTP component supports the following Proxy servers:
Proxy | Name |
---|---|
SOCKS4 | SOCKS4 proxy. |
SOCKS4A | SOCKS4A proxy (capable of resolving domain names). |
SOCKS5 | SOCKS5 proxy. |
HTTP CONNECT | HTTP proxy using CONNECT method. |
The SSH client classes that implement the ISecureShellClient
interface can share the connection with other protocol sessions. To reuse connection of another SSH session, use the ReuseConnection
method. All the SFTP, SCP, or SSH sessions use the same underlying SSH connection.
// Create a new instance of the Sftp class.
using (Sftp sftp1 = new Sftp())
{
// Connect to the server.
sftp1.Connect(serverName);
// Authenticate the user
sftp1.Authenticate(userName, password);
Sftp sftp2 = new Sftp();
// Reuse the connection from the sftp1 instance.
sftp2.ReuseConnection(sftp1);
// Download files
sftp1.DownloadFile("/data/file1.dat", @"c:\data\file1.dat");
sftp2.DownloadFile("/data/file2.dat", @"c:\data\file2.dat");
}
' Create a new instance of the Sftp class.
Using sftp1 As New Sftp()
' Connect to the server.
sftp1.Connect(serverName)
' Authenticate the user
sftp1.Authenticate(userName, password)
Dim sftp2 As New Sftp()
' Reuse the connection from the sftp1 instance.
sftp2.ReuseConnection(sftp1)
' Download files
sftp1.DownloadFile("/data/file1.dat", "c:\data\file1.dat")
sftp2.DownloadFile("/data/file2.dat", "c:\data\file2.dat")
End Using
Ultimate SFTP supports many authentication methods including: password, public/private key, interactive, Kerberos and NTLM.
To authenticate a user with password-based authentication, just use this Authenticate
method overload. The first parameter is the name of the user, the second one is the user's password.
public void DoConnect()
{
// Create a new class instance.
Sftp client = new Sftp();
client.HostKeyVerifying += HostKeyVerifying;
// Connect to the SFTP server.
client.Connect("myserver");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();
}
void HostKeyVerifying(object sender, HostKeyVerifyingEventArgs e)
{
Console.WriteLine("Host key: " + e.HostKey);
}
Public Sub DoConnect()
' Create a new class instance.
Dim client As New Sftp()
AddHandler client.HostKeyVerifying, AddressOf HostKeyVerifying
' Connect to the SFTP server.
client.Connect("myserver")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()
End Sub
Private Sub HostKeyVerifying(ByVal sender As Object, ByVal e As HostKeyVerifyingEventArgs)
Console.WriteLine("Host key: " & e.HostKey)
End Sub
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver", 22);
// Authenticate user with a private key.
client.Authenticate("userName", "c:\\privateKey.key", "pkeypassword");
// It's possible to use both username/password and private key to authenticate.
// client.Authenticate("userName", "password", "c:\\privateKey.key", "pkeypassword");
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver", 22)
' Authenticate user with a private key.
client.Authenticate("userName", "c:\privateKey.key", "pkeypassword")
' It's possible to use both username/password and private key to authenticate.
' client.Authenticate("userName", "password", "c:\\privateKey.key", "pkeypassword");
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()
It is more desirable to use public key cryptography rather than using a password to authenticate. The SSH server keeps a database of public keys for each account - exact details of this depends on the server (OpenSSH keeps the public keys in ~/.ssh/authorized_keys file in each account's home directory). A public key has a corresponding private key that is kept secret by the client. To authenticate to the server using public key cryptography, you need this private key. To authenticate using your private key, simply call the Authenticate method with the SecureShellPrivateKey
object created from the provided name of the private key and its passphrase. If you find out that your private key format is not supported by our component, please do not hesitate to send a request to us at support@componentpro.com.
Some SSH servers require interactive authentication to authenticate users. In general, they issue a series of question and ask the client to response. The most common question is "Please provide your password" and the client provides a valid password for initiating the verification. To be notified about the questions from the server and provide responses, register a handler of the KeyboardInteractiveAuthentication
event.
public void DoConnect()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("userName", "password", KeyboardInteractiveAuthenticationHandler);
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();
}
private void KeyboardInteractiveAuthenticationHandler(object sender, KeyboardInteractiveAuthenticationEventArgs e)
{
// If we have a request
if (e.Requests.Count > 0)
{
// If the first request is the string "Password: ".
if (string.Compare(e.Requests[0].Prompt, "Password: ", StringComparison.InvariantCultureIgnoreCase) == 0)
{
// We provide password as the response
e.Requests[0].Response = "mypass";
}
}
}
Public Sub DoConnect()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("userName", "password", AddressOf KeyboardInteractiveAuthenticationHandler)
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()
End Sub
Private Sub KeyboardInteractiveAuthenticationHandler(ByVal sender As Object, ByVal e As KeyboardInteractiveAuthenticationEventArgs)
' If we have a request
If e.Requests.Count > 0 Then
' If the first request is the string "Password: ".
If String.Compare(e.Requests(0).Prompt, "Password: ", StringComparison.InvariantCultureIgnoreCase) = 0 Then
' We provide password as the response
e.Requests(0).Response = "mypass"
End If
End If
End Sub
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("myserver");
// Initialize GSSAPI for NTLM single sign-on
SecureShellGssApiCredentials credentials = new SecureShellGssApiCredentials();
credentials.SetMechanisms(SecureShellGssApiMechanisms.Ntlm);
// Log in using NTLM single sign-on
client.Authenticate(credentials);
// ...
}
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Initialize GSSAPI for NTLM single sign-on
Dim credentials As New SecureShellGssApiCredentials()
credentials.SetMechanisms(SecureShellGssApiMechanisms.Ntlm)
' Log in using NTLM single sign-on
client.Authenticate(credentials)
' ...
End Using
This example demonstrates how to use the GSSAPI NTLM authentication mechanism if the server supports it.
You can also choose the username/password/domain authentication method as shown in this example.
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("myserver");
// Initialize GSSAPI for NTLM single sign-on
SecureShellGssApiCredentials credentials = new SecureShellGssApiCredentials(authUsername, authApiPassword, authDomain);
credentials.SetMechanisms(SecureShellGssApiMechanisms.Ntlm);
// Log in using NTLM
client.Authenticate(credentials);
// ...
}
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Initialize GSSAPI for NTLM single sign-on
Dim credentials As New SecureShellGssApiCredentials(authUsername, authApiPassword, authDomain)
credentials.SetMechanisms(SecureShellGssApiMechanisms.Ntlm)
' Log in using NTLM
client.Authenticate(credentials)
' ...
End Using
In addition to the capability of uploading and downloading a single file, you can also specify ZLIB compression mode, ASCII or Binary transfer mode. The library comes with a built-in support for long path on Windows. It also allow you to resume interupted file transfer, upload/download file to/from another file system other than local disk file system.
It is very easy to upload data from a local file or a stream. To upload data from a stream to the remote SFTP server, simply use the UploadFile
method which has two parameters, or another version of the UploadFile
method for transferring data starting from a specific stream position. The first parameter is the data stream object and the second one is the remote file path. It returns the number of bytes transferred.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
FileStream fi = new FileStream("c:\\test.dat", FileMode.Open);
// Upload data from a stream to '/test.dat'.
client.UploadFile(fi, "/test.dat");
fi.Close();
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
Dim fi As New FileStream("c:\test.dat", FileMode.Open)
' Upload data from a stream to '/test.dat'.
client.UploadFile(fi, "/test.dat")
fi.Close()
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Create new file
FileStream fo = new FileStream("c:\\file.dat", FileMode.Create);
// Download remote file '/test.dat' to 'c:\test.dat'
client.DownloadFile("/test.dat", fo);
fo.Close();
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Create new file
Dim fo As New FileStream("c:\file.dat", FileMode.Create)
' Download remote file '/test.dat' to 'c:\test.dat'
client.DownloadFile("/test.dat", fo)
fo.Close()
' ...
' Disconnect.
client.Disconnect()
To download data from the remote file to a stream, simply use the DownloadFile
method which has two parameters, or another version of the DownloadFile
method for transferring data starting from a specific stream position. The first parameter is the remote file path and the second one is the data stream object. It returns the number of bytes transferred.
The compression mode is enabled by setting the Config.EnableCompression
to true
before connecting to the server:
// Create a new instance of the Sftp class.
Sftp client = new Sftp();
// Turn on transfer compression. By default, the EnableCompression property is set to false.
client.Config.EnableCompression = true;
// If you wish to turn off transfer compression
// client.EnableCompression = false;
// Connect to the server
client.Connect("server", 22);
// ...
client.Disconnect();
' Create a new instance of the Sftp class.
Dim client As New Sftp()
' Turn on transfer compression. By default, the EnableCompression property is set to false.
client.Config.EnableCompression = True
' If you wish to turn off transfer compression
' client.EnableCompression = false;
' Connect to the server
client.Connect("server", 22)
' ...
client.Disconnect()
// Create a new Sftp instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Resume uploading local file 'c:\test.dat' to '/test.dat'.
client.ResumeUploadFile("c:\\test.dat", "/test.dat");
// ...
// Disconnect.
client.Disconnect();
' Create a new Sftp instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Resume uploading local file 'c:\test.dat' to '/test.dat'.
client.ResumeUploadFile("c:\test.dat", "/test.dat")
' ...
' Disconnect.
client.Disconnect()
To resume a file upload, use the ResumeUploadFile
method. Similarly, to resume a file download, use the ResumeDownloadFile
method. The following code snippet demonstrates how to continue a transfer that was interrupted or canceled.
Ultimate SFTP supports two transfer mode: Binary (default) and ASCII. In binary mode (by setting the TransferType
property to Binary), data is transferred as is without any processing. When text data is transferred between platforms that use different end-of-line sequences (Windows use <CR><LF>
Unix uses <LF>
), the transferred text data is unchanged and may be unfriendly presented to the user. It's essential to have the library convert the sequences automatically. To achieve that, set the TransferType
property to Ascii
.
// Set server OS to Unix
client.ServerOs = RemoteServerOs.Unix;
// Set transfer type to ASCII
client.TransferType = FileTransferType.Ascii;
// Upload TXT files.
client.Upload(@"c:\data\*.txt", "/data");
' Set server OS to Unix
client.ServerOs = RemoteServerOs.Unix
' Set transfer type to ASCII
client.TransferType = FileTransferType.Ascii
' Upload TXT files.
client.Upload("c:\data\*.txt", "/data")
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Download remote file '/test.dat' to 'c:\test.dat'
client.DownloadFile("/test.dat", "c:\\test.dat", 1024, 1024, -1);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Download remote file '/test.dat' to 'c:\test.dat'
client.DownloadFile("/test.dat", "c:\test.dat", 1024, 1024, -1)
' ...
' Disconnect.
client.Disconnect()
To download part of a remote file, specify the remoteOffset
and length
parameters of this DownloadFile
method overload.
Ultimate SFTP supports two transfer modes: Binary and ASCII. The SFTP protocol's maximum supported file size is 2^63 bytes = 9,223,372 TB
. However, some underlying filesystems do not support large file size. FAT16 and FAT32 are two examples; they support 2GB and 4GB maximum file size respectively. For other filesystems, see this table.
There is still a workaround for the filesystems that can't store files larger than 4GB. The stream-based file transfer API supports reading file from small pieces and combine them all together to have the large file.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Upload local file 'c:\test.dat' to '/test.dat'.
client.UploadFile("c:\\test.dat", "/test.dat");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Upload local file 'c:\test.dat' to '/test.dat'.
client.UploadFile("c:\test.dat", "/test.dat")
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
string localPath = @"D:\Data\dailyReport.xml";
string remotePath = "/Data/reports.xml";
long localFileLength = new FileInfo(localPath).Length;
long remoteFileLength = client.GetFileLength(remotePath);
// Append header for 'dailyReport.xml' to 'reports.xml' on the server from memory
string reportHeader = string.Format("<path>{0}</path>\n", localPath);
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(reportHeader));
client.UploadFile(ms, remotePath,
remoteFileLength, // Remote offset
ms.Length); // The number of bytes to upload
// Update remote length
remoteFileLength += ms.Length;
// Append data from 'dailyReport.xml' to 'reports.xml' on the server
client.UploadFile(localPath, remotePath,
0, // Local offset
remoteFileLength, // Remote offset
localFileLength); // The number of bytes to upload
// Disconnect.
client.Disconnect();
}
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
Dim localPath As String = "D:\Data\dailyReport.xml"
Dim remotePath As String = "/Data/reports.xml"
Dim localFileLength As Long = (New FileInfo(localPath)).Length
Dim remoteFileLength As Long = client.GetFileLength(remotePath)
' Append header for 'dailyReport.xml' to 'reports.xml' on the server from memory
Dim reportHeader As String = String.Format("<path>{0}</path>" & vbLf, localPath)
Dim ms As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(reportHeader))
client.UploadFile(ms, remotePath, remoteFileLength, ms.Length) ' The number of bytes to upload - Remote offset
' Update remote length
remoteFileLength += ms.Length
' Append data from 'dailyReport.xml' to 'reports.xml' on the server
client.UploadFile(localPath, remotePath, 0, remoteFileLength, localFileLength) ' The number of bytes to upload - Remote offset - Local offset
' Disconnect.
client.Disconnect()
End Using
The UploadFile
and DownloadFile
methods make it possible to upload or download a part of a file. This is often used for appending data to an existing file, or to resume broken transfers. Of course, it is possible to write/read data to/from any other position in a file as well.
To upload and download specific file part, use three additional parameters: local offset, remote offset, and the number of bytes you want to transfer. Local offset is not required for stream-based methods - data is read/written from/to the current stream position.
To download a file from an SFTP server to another file system, use the CopyTo
methods.
The following example demonstrates how to connect to FTP and SFTP servers, and use the CopyTo
method to directly copy a file from the SFTP file system to the FTP file system.
// 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 'my blog on SFTP file system.txt' file from the SFTP file system to the FTP file system.
sftp.CopyTo("my blog on SFTP file system.txt", ftpsys, "blog.txt");
ftpsys.Disconnect();
sftp.Disconnect();
' 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 'my blog on SFTP file system.txt' file from the SFTP file system to the FTP file system.
sftp.CopyTo("my blog on SFTP file system.txt", ftpsys, "blog.txt")
ftpsys.Disconnect()
sftp.Disconnect()
// 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.
sftp.CopyTo("blog.txt", ftpsys, "my blog on FTP file system.txt");
ftpsys.Disconnect();
sftp.Disconnect();
' 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.
sftp.CopyTo("blog.txt", ftpsys, "my blog on FTP file system.txt")
ftpsys.Disconnect()
sftp.Disconnect()
To upload a file from another file system to an FTP server, simply use the CopyTo
methods.
The following example demonstrates how to connect to FTP and SFTP servers, and use the CopyTo
method to directly copy a file from the FTP file system to the SFTP file system.
Ultimate SFTP allows you to break a large file into multiple ones of a smaller set size so that the file can be downloaded faster. The following code snippet illustrates how to download many small pieces of a large file simultaneously.
static void Main()
{
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
client.Progress += ClientOnProgress;
client.MultiPartDownload("/folder/remotefile.dat", "c:\\localfile.dat", 5, DownloadErrorHandler, DownloadCompletedHandler);
// ...
}
}
static void DownloadErrorHandler(MultiPartDownloadErrorEventArgs e)
{
Console.WriteLine("Error: " + e.Error.Message);
Console.Write("Do you want to retry (y/n)?");
int c = Console.Read();
if (c == 'y')
e.Retry = true;
}
static void DownloadCompletedHandler(MultiPartDownloadResult result)
{
Console.WriteLine("Success: " + result.Success);
}
private static void ClientOnProgress(object sender, FileSystemProgressEventArgs e)
{
Console.WriteLine("Progression Percentage: " + e.Percentage);
}
Shared Sub Main()
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
AddHandler client.Progress, AddressOf ClientOnProgress
client.MultiPartDownload("/folder/remotefile.dat", "c:\localfile.dat", 5, AddressOf DownloadErrorHandler, AddressOf DownloadCompletedHandler)
' ...
End Using
End Sub
Private Shared Sub DownloadErrorHandler(ByVal e As MultiPartDownloadErrorEventArgs)
Console.WriteLine("Error: " & e.Error.Message)
Console.Write("Do you want to retry (y/n)?")
Dim c As Integer = Console.Read()
If c = AscW("y"c) Then
e.Retry = True
End If
End Sub
Private Shared Sub DownloadCompletedHandler(ByVal result As MultiPartDownloadResult)
Console.WriteLine("Success: " & result.Success)
End Sub
Private Shared Sub ClientOnProgress(ByVal sender As Object, ByVal e As FileSystemProgressEventArgs)
Console.WriteLine("Progression Percentage: " & e.Percentage)
End Sub
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
// Download a file to a directory with extra long path
client.DownloadFile("/remote file.dat", @"c:\very long long long long long long long long long long long long long long long long long long long long long long long long long long long\very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long\file.dat");
// Upload multiple files from a directory with extra long path
client.Upload(@"c:\very long long long long long long long long long long long long long long long long long long long long long long long long long long long\very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long", "/data");
// ...
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
' Download a file to a directory with extra long path
client.DownloadFile("/remote file.dat", "c:\very long long long long long long long long long long long long long long long long long long long long long long long long long long long\very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long\file.dat")
' Upload multiple files from a directory with extra long path
client.Upload("c:\very long long long long long long long long long long long long long long long long long long long long long long long long long long long\very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long", "/data")
' ...
End Using
All the file and directory management API permit an extended-length path for a maximum total path length of 32,767
characters.
This section covers the single file features. You can easily check existence, delete, rename/move, calculate checksum, get file info, set permissions or create remote files with a single line of code.
To delete a remote file, just call the DeleteFile
method. The following code example shows how to delete a remote file on the SFTP server:
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Delete remote file '/test.dat'.
client.DeleteFile("/test.dat");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Delete remote file '/test.dat'.
client.DeleteFile("/test.dat")
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Determine whether file 'myFile.dat' exists or not.
if (client.FileExists("/myFile.dat"))
Console.WriteLine("File '/myFile.dat' exists");
else
Console.WriteLine("File '/myFile.dat' does not exist");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Determine whether file 'myFile.dat' exists or not.
If client.FileExists("/myFile.dat") Then
Console.WriteLine("File '/myFile.dat' exists")
Else
Console.WriteLine("File '/myFile.dat' does not exist")
End If
' ...
' Disconnect.
client.Disconnect()
To determine whether a remote file exists or not, you can use the FileExists
method. You just need to pass the path of the remote file to check to the FileExists
method, and it returns a boolean value indicating the specified file exists or not.
To rename a file, use the Rename
method. It also supports moving a remote file to another location.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Rename remote file '/file.dat' to 'myfile.dat'
client.Rename("/file.dat", "/myfile.dat");
// Move a file
client.Rename("/file2.dat", "/new-folder/file2.dat");
// Rename a remote directory
client.Rename("/album-folder", "/old-album-folder");
// Move a directory
client.Rename("/album-folder2", "/new-folder/album-folder2");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Rename remote file '/file.dat' to 'myfile.dat'
client.Rename("/file.dat", "/myfile.dat")
' Move a file
client.Rename("/file2.dat", "/new-folder/file2.dat")
' Rename a remote directory
client.Rename("/album-folder", "/old-album-folder")
' Move a directory
client.Rename("/album-folder2", "/new-folder/album-folder2")
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
string checksum = client.GetFileChecksum(ComponentPro.IO.FileChecksumType.SHA1, "/data/test.dat");
}
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
Dim checksum As String = client.GetFileChecksum(ComponentPro.IO.FileChecksumType.SHA1, "/data/test.dat")
End Using
Some SFTP servers support checksum calculation so the client can make use of the checksums to ensure that the files are uploaded/downloaded correctly by comparing the server checksum with of the local files.
You can easily get the length of a remote file with the GetFileLength
method of the Sftp
class.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get size in bytes of the remote file '/test.dat'.
long length = client.GetFileLength("/test.dat");
Console.WriteLine("'/test.dat' file length is: {0} bytes", length);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get size in bytes of the remote file '/test.dat'.
Dim length As Long = client.GetFileLength("/test.dat")
Console.WriteLine("'/test.dat' file length is: {0} bytes", length)
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get information of remote file '/test.dat'.
SftpFileInfo info = (SftpFileInfo)client.GetItemInfo("/test.dat");
Console.WriteLine("Name: {0}, FullName: {1}, Permissions: {2}", info.Name, info.FullName, info.Permissions);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get information of remote file '/test.dat'.
Dim info As SftpFileInfo = CType(client.GetItemInfo("/test.dat"), SftpFileInfo)
Console.WriteLine("Name: {0}, FullName: {1}, Permissions: {2}", info.Name, info.FullName, info.Permissions)
' ...
' Disconnect.
client.Disconnect()
To get information of a remote file, just use the GetItemInfo
method of the Sftp
class.
To get last modification date and time of a remote file or directory, use the GetLastWriteTime
method of the Ftp class. To set it, use the SetLastWriteTime
method. The following example shows you how easy it is to do that:
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get modified date and time of the remote file '/test.dat'.
DateTime modifiedDateTime = client.GetLastWriteTime("/test.dat");
Console.WriteLine("Modified date and time of '/test.dat' is: {0}", modifiedDateTime);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get modified date and time of the remote file '/test.dat'.
Dim modifiedDateTime As Date = client.GetLastWriteTime("/test.dat")
Console.WriteLine("Modified date and time of '/test.dat' is: {0}", modifiedDateTime)
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Set file attributes
SftpFileAttributes attrs = new SftpFileAttributes();
attrs.Permissions = SftpFilePermissions.OwnerExecute | SftpFilePermissions.OwnerWrite |
SftpFilePermissions.OwnerRead;
attrs.LastWriteTime = DateTime.Now;
client.SetFileAttributes("/file.dat", attrs);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Set file attributes
Dim attrs As New SftpFileAttributes()
attrs.Permissions = SftpFilePermissions.OwnerExecute Or SftpFilePermissions.OwnerWrite Or SftpFilePermissions.OwnerRead
attrs.LastWriteTime = Date.Now
client.SetFileAttributes("/file.dat", attrs)
' ...
' Disconnect.
client.Disconnect()
To set file attributes including permission, creation time, last write time, user id, and group, use the SetFileAttributes
method. The following example shows you how to accomplish that.
To create a new empty file, create an instance of the FtpFileInfo
class and call the Create
method of that object.
// Create a new class instance.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
FileInfoBase info = client.CreateFileInfo("/newfile", true);
// Create a new file.
info.Create();
}
' Create a new class instance.
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
Dim info As FileInfoBase = client.CreateFileInfo("/newfile", True)
' Create a new file.
info.Create()
End Using
With a single line of code, you can transfer multiple files at once. Ultimate SFTP allows using file masks as parameter for multi-file operations such as upload, download, delete, move, and set permissions. The library also let you transfer files simultaneously using multiple threads.
File masks consist of three types of symbols and their combinations:
'**' is the special wildcard that is used to match any character, including directory separators. See this for more details. The above examples show that a file mask with only fixed characters refers to a single unique file (e.g. file mask my-picture.jpg refers to, and only to, a file named my-picture.jpg), while file masks containing wildcards such as ‘?’ or/and ‘*’ can refer to both single or multiple files.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Upload all files and subdirectories from local folder 'c:\temp' to the remote dir '/temp'
client.Upload("c:\\temp", "/temp");
// Upload all directories, subdirectories, and files that match the specified search pattern from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\\myfolder2", "/myfolder2", "*.cs");
// or you can simply put wildcard masks in the source path, our component will automatically parse it.
// upload all *.css files from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\\myfolder2\\*.css", "/myfolder2");
// Upload *.cs and *.vb files from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\\myfolder2\\*.cs;*.vb", "/myfolder2");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Upload all files and subdirectories from local folder 'c:\temp' to the remote dir '/temp'
client.Upload("c:\temp", "/temp")
' Upload all directories, subdirectories, and files that match the specified search pattern from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\myfolder2", "/myfolder2", "*.cs")
' or you can simply put wildcard masks in the source path, our component will automatically parse it.
' upload all *.css files from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\myfolder2\*.css", "/myfolder2")
' Upload *.cs and *.vb files from local folder 'c:\myfolder2' to remote folder '/myfolder2'.
client.Upload("c:\myfolder2\*.cs;*.vb", "/myfolder2")
' ...
' Disconnect.
client.Disconnect()
To upload multiple files (e.g. all ".dat" files), use the Upload
methods. The most used Upload
method overload just needs two parameters. The first one is the path to the local directory and the second one is the path to the remote directory.
To download multiple remote files (e.g. all ".dat" files), use the Download
methods. The most used Download
method overload just needs two parameters. The first one is the path to the remote directory and the second one is the path to the local directory.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Get all directories, subdirectories, and files from remote folder '/myfolder' to 'c:\myfolder'.
client.Download("/myfolder", "c:\\myfolder");
// Get all directories, subdirectories, and files that match the specified search pattern from remote folder '/myfolder2' to 'c:\myfolder2'.
client.Download("/myfolder2", "c:\\myfolder2", "*.cs");
// or you can simply put wildcard masks in the source path, our component will automatically parse it.
// download all *.css files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.Download("/myfolder2/*.css", "c:\\myfolder2");
// Download *.cs and *.vb files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.Download("/myfolder2/*.cs;*.vb", "c:\\myfolder2");
// Get files in the folder '/myfolder2' only.
TransferOptions opt = new TransferOptions(true, false, OptionValue.Auto, null, FileOverwriteMode.Overwrite, SymlinksResolveAction.Skip);
client.Download("/myfolder2", "c:\\myfolder2", opt);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Get all directories, subdirectories, and files from remote folder '/myfolder' to 'c:\myfolder'.
client.Download("/myfolder", "c:\myfolder")
' Get all directories, subdirectories, and files that match the specified search pattern from remote folder '/myfolder2' to 'c:\myfolder2'.
client.Download("/myfolder2", "c:\myfolder2", "*.cs")
' or you can simply put wildcard masks in the source path, our component will automatically parse it.
' download all *.css files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.Download("/myfolder2/*.css", "c:\myfolder2")
' Download *.cs and *.vb files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.Download("/myfolder2/*.cs;*.vb", "c:\myfolder2")
' Get files in the folder '/myfolder2' only.
Dim opt As New TransferOptions(True, False, OptionValue.Auto, Nothing, FileOverwriteMode.Overwrite, SymlinksResolveAction.Skip)
client.Download("/myfolder2", "c:\myfolder2", opt)
' ...
' Disconnect.
client.Disconnect()
public void DoUpload()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Authenticate.
client.Authenticate("test", "test");
// ...
client.TransferConfirm += client_TransferConfirm;
client.Progress += client_Progress;
try
{
TransferOptions opt = new TransferOptions("*.*", FileOverwriteMode.Confirm);
// Get all directories, subdirectories, and files in local folder 'c:\myfolder' to remote folder '/myfolder'.
client.Upload("c:\\myfolder", "/myfolder", opt);
}
catch (Exception exc)
{
Console.WriteLine("Error: " + exc.Message);
}
// ...
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, ComponentPro.IO.FileSystemProgressEventArgs e)
{
// Show progress info.
Console.WriteLine("Current File: %{0} completed", e.Percentage);
Console.WriteLine("Total: %{0} completed", e.TotalPercentage);
switch (e.State)
{
case TransferState.StartUploadingFile:
if (e.SourcePath.EndsWith(".exe"))
{
// Skip all .exe files
e.Skip = true;
}
else if (e.SourcePath.StartsWith(@"C:\MyFolder"))
{
// Change the source file path if it starts with "C:\MyFolder"
e.SourcePath = e.SourcePath.Replace(@"C:\MyFolder", @"C:\MySecondFolder");
}
break;
}
}
void client_TransferConfirm(object sender, ComponentPro.IO.TransferConfirmEventArgs e)
{
if (e.Exception != null)
Console.WriteLine("Error: " + e.Exception.Message);
if (e.ConfirmReason == TransferConfirmReason.FileAlreadyExists)
{
// Skip the existing file.
e.NextAction = TransferConfirmNextActions.Skip;
}
Console.Write("Do you want to (r)etry or (s)kip?");
string key = Console.ReadLine();
if (key == "r")
e.NextAction = TransferConfirmNextActions.Retry;
else if (key == "s")
e.NextAction = TransferConfirmNextActions.Skip;
else
// Cancel the operation.
e.NextAction = TransferConfirmNextActions.Cancel;
}
Public Sub DoUpload()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Authenticate.
client.Authenticate("test", "test")
' ...
AddHandler client.TransferConfirm, AddressOf client_TransferConfirm
AddHandler client.Progress, AddressOf client_Progress
Try
Dim opt As New TransferOptions("*.*", FileOverwriteMode.Confirm)
' Get all directories, subdirectories, and files in local folder 'c:\myfolder' to remote folder '/myfolder'.
client.Upload("c:\myfolder", "/myfolder", opt)
Catch exc As Exception
Console.WriteLine("Error: " & exc.Message)
End Try
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As ComponentPro.IO.FileSystemProgressEventArgs)
' Show progress info.
Console.WriteLine("Current File: %{0} completed", e.Percentage)
Console.WriteLine("Total: %{0} completed", e.TotalPercentage)
Select Case e.State
Case TransferState.StartUploadingFile
If e.SourcePath.EndsWith(".exe") Then
' Skip all .exe files
e.Skip = True
ElseIf e.SourcePath.StartsWith("C:\MyFolder") Then
' Change the source file path if it starts with "C:\MyFolder"
e.SourcePath = e.SourcePath.Replace("C:\MyFolder", "C:\MySecondFolder")
End If
End Select
End Sub
Private Sub client_TransferConfirm(ByVal sender As Object, ByVal e As ComponentPro.IO.TransferConfirmEventArgs)
If e.Exception IsNot Nothing Then
Console.WriteLine("Error: " & e.Exception.Message)
End If
If e.ConfirmReason = TransferConfirmReason.FileAlreadyExists Then
' Skip the existing file.
e.NextAction = TransferConfirmNextActions.Skip
End If
Console.Write("Do you want to (r)etry or (s)kip?")
Dim key As String = Console.ReadLine()
If key = "r" Then
e.NextAction = TransferConfirmNextActions.Retry
ElseIf key = "s" Then
e.NextAction = TransferConfirmNextActions.Skip
Else
' Cancel the operation.
e.NextAction = TransferConfirmNextActions.Cancel
End If
End Sub
The TransferConfirm
and Progress
events of the Sftp
class give you the ease of controlling files to upload and showing progress while transferring data. The following example illustrates how to register event handlers to the TransferConfirm
and Progress
events to monitor the file upload process.
To limit the files that will be uploaded, you can add filtering masks to the localDirectoryPath
parameter of the Upload
method. However, when you want to exclude unwanted files and directories, you need to use the SearchCondition
class or its Fluent API.
client.Upload("c:\\mydata", "/data", new NameSearchCondition("*.txt") - new NameSearchCondition("file*"));
// or
client.Upload("c:\\mydata", "/data", new NameSearchCondition("*.txt").ExcludeMasks("file*"));
client.Upload("c:\mydata", "/data", New NameSearchCondition("*.txt") - New NameSearchCondition("file*"))
' or
client.Upload("c:\mydata", "/data", (New NameSearchCondition("*.txt")).ExcludeMasks("file*"))
// All files in "C:\data" will be copied to "/data" without keeping their directory structure.
TransferOptions opt = new TransferOptions();
opt.Flatten = true;
// Upload files.
client.Upload(@"C:\data", "/data", opt);
// All files in "C:\A" and "C:\B" will be uploaded to "/mydata" without keeping their directory structure.
client.Upload(new string[] {@"C:\A", @"C:\B"}, "/mydata", opt);
' All files in "C:\data" will be copied to "/data" without keeping their directory structure.
Dim opt As New TransferOptions()
opt.Flatten = True
' Upload files.
client.Upload("C:\data", "/data", opt)
' All files in "C:\A" and "C:\B" will be uploaded to "/mydata" without keeping their directory structure.
client.Upload(New String() {"C:\A", "C:\B"}, "/mydata", opt)
The TransferOptions
class can even be used to upload (or download) files from multiple directories (or even a whole directory tree) into a single directory - just set the Flatten property to true and call the Upload or Download method. For example, when uploading files "C:\A\a.txt"
and "C:\B\b.txt"
to "/MyData"
directory, both the files end up in the "/MyData"
directory (and no "A"
or "B"
directories are created).
Downloading files and directories from the remote SFTP server to the local disk is quite simple. All that needs to occur is passing appropriate server information such as hostname, port, username, password/private key and the number of threads to the Download
method of the Sftp
class.
The following steps illustrate how to use the Download
to download files and directories.
static void Main()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the server.
client.Connect("server");
// Authenticate.
client.Authenticate("user", "pass");
client.CommandResponse += client_ResponseRead;
// You can register the ThreadStateChanged event here or in the client_Progress event handler as shown below.
client.ThreadStateChanged += Thread_StateChanged;
client.Progress += client_Progress;
// ...
// Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
client.Download("/my folder", "c:\\my folder", 3, true);
// ...
client.Disconnect();
}
static void client_Progress(object sender, FileSystemProgressEventArgs e)
{
// You can access the threads used for the multi-thread file operation here.
// Uncomment the following code to register the StateChanged event of each thread.
//if (e.State == TransferState.DirectoryStructureBuilt)
//{
// for (int i = 0; i < e.TransferStatistics.Threads.Count; i++)
// {
// e.TransferStatistics.Threads[i].StateChanged += Thread_StateChanged;
// }
//}
// When the multi-thread operation completes the status is MultiFileOperationCompleted.
if (e.State == TransferState.MultiFileOperationCompleted)
Console.WriteLine("File transfer completed");
}
static long _threadsCompleted;
static void Thread_StateChanged(object sender, TransferThreadStateChangedEventArgs e)
{
if (e.State == TransferThreadState.Stopped) // The thread is stopped
{
TransferThreadInfo info = (TransferThreadInfo)sender;
Console.WriteLine(string.Format("Thread ID {0} completed", info.ThreadId));
Interlocked.Increment(ref _threadsCompleted);
if (Interlocked.Read(ref _threadsCompleted) == 3)
{
Console.WriteLine("Multi-threads file transfer completed");
}
}
}
static void client_ResponseRead(object sender, CommandResponseEventArgs e)
{
Sftp client = (Sftp)sender;
if (client.ThreadId >= 0)
if (e.Command != null)
Console.WriteLine("Thread: {0} - CMD> {1}", client.ThreadId,
e.Command);
else
Console.WriteLine("Thread: {0} - RESPONSE> {1}", client.ThreadId,
e.Response);
}
Shared Sub Main()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the server.
client.Connect("server")
' Authenticate.
client.Authenticate("user", "pass")
AddHandler client.CommandResponse, AddressOf client_ResponseRead
' You can register the ThreadStateChanged event here or in the client_Progress event handler as shown below.
AddHandler client.ThreadStateChanged, AddressOf Thread_StateChanged
AddHandler client.Progress, AddressOf client_Progress
' ...
' Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
client.Download("/my folder", "c:\my folder", 3, True)
' ...
client.Disconnect()
End Sub
Private Shared Sub client_Progress(ByVal sender As Object, ByVal e As FileSystemProgressEventArgs)
' You can access the threads used for the multi-thread file operation here.
' Uncomment the following code to register the StateChanged event of each thread.
'if (e.State == TransferState.DirectoryStructureBuilt)
'{
' for (int i = 0; i < e.TransferStatistics.Threads.Count; i++)
' {
' e.TransferStatistics.Threads[i].StateChanged += Thread_StateChanged;
' }
'}
' When the multi-thread operation completes the status is MultiFileOperationCompleted.
If e.State = TransferState.MultiFileOperationCompleted Then
Console.WriteLine("File transfer completed")
End If
End Sub
Private Shared _threadsCompleted As Long
Private Shared Sub Thread_StateChanged(ByVal sender As Object, ByVal e As TransferThreadStateChangedEventArgs)
If e.State = TransferThreadState.Stopped Then ' The thread is stopped
Dim info As TransferThreadInfo = CType(sender, TransferThreadInfo)
Console.WriteLine(String.Format("Thread ID {0} completed", info.ThreadId))
Interlocked.Increment(_threadsCompleted)
If Interlocked.Read(_threadsCompleted) = 3 Then
Console.WriteLine("Multi-threads file transfer completed")
End If
End If
End Sub
Private Shared Sub client_ResponseRead(ByVal sender As Object, ByVal e As CommandResponseEventArgs)
Dim client As Sftp = CType(sender, Sftp)
If client.ThreadId >= 0 Then
If e.Command IsNot Nothing Then
Console.WriteLine("Thread: {0} - CMD> {1}", client.ThreadId, e.Command)
Else
Console.WriteLine("Thread: {0} - RESPONSE> {1}", client.ThreadId, e.Response)
End If
End If
End Sub
// Upload "*.dat" files from "C:\data" to "/content" remote directory on the SFTP server.
// Existing files will be skipped.
FileSystemTransferStatistics stat = client.Upload(@"C:\data\*.dat", "/content", false, FileOverwriteMode.Skip);
Console.WriteLine("Total files: {0}. Total dirs: {1}", stat.TotalFiles, stat.TotalDirectories);
Console.WriteLine("Total files skipped: {0}", stat.FilesSkipped);
Console.WriteLine("Total size: {0}", stat.TotalBytes);
' Upload "*.dat" files from "C:\data" to "/content" remote directory on the SFTP server.
' Existing files will be skipped.
Dim stat As FileSystemTransferStatistics = client.Upload("C:\data\*.dat", "/content", False, FileOverwriteMode.Skip)
Console.WriteLine("Total files: {0}. Total dirs: {1}", stat.TotalFiles, stat.TotalDirectories)
Console.WriteLine("Total files skipped: {0}", stat.FilesSkipped)
Console.WriteLine("Total size: {0}", stat.TotalBytes)
The result of a multiple file operation can be accessed through a FileSystemTransferStatistics
object. It provides useful information shown below:
FilesProcessed
/DirectoriesProcessed
- The number of files/directories processedFilesSkipped
/DirectoriesSkipped
- The number of files/directories skippedTotalFiles
/TotalDirectories
- The total number of files/directoriesTotalBytes
, TotalBytesSkipped
, TotalBytesTransferred
- The total number of bytes, skipped bytes, and processed bytesBytesPerSecond
- Bytes per secondFileList
- List of files and directories (available only when TransferOptions.RetainFileList
is true
)By default, the data is transferred in binary mode without any processing. However, when transferring text data between platforms which use different end-of-line sequences (Windows use <CR><LF>
, Unix uses <LF>
), it's essential to have the sequences automatically converted by setting the transfer mode to ASCII.
In a multi-file transfer, to determine whether a file should be transferred in ASCII or Binary mode, Ultimate SFTP uses the AsciiFileSearchConditions
property to check against the processing file. If a file matches that criteria, the file will be transferred in ASCII mode; otherwise, binary mode is used.
client.AsciiFileSearchConditions = new SearchCondition[] { new NameSearchCondition("*.txt") };
// Upload TXT files.
// TXT will be transferred in ASCII mode, all other files will be transferred in Binary mode
client.Upload(@"c:\data\*.txt", "/data");
client.AsciiFileSearchConditions = New SearchCondition() { New NameSearchCondition("*.txt") }
' Upload TXT files.
' TXT will be transferred in ASCII mode, all other files will be transferred in Binary mode
client.Upload("c:\data\*.txt", "/data")
// File time will be restored after a transfer.
client.RestoreFileProperties = true;
// Upload DOC files.
client.Upload(@"c:\data\*.doc", "/data");
' File time will be restored after a transfer.
client.RestoreFileProperties = True
' Upload DOC files.
client.Upload("c:\data\*.doc", "/data")
By default, Ultimate SFTP does not synchronize creation, last access and last write time of a file or directory after uploading or downloading. To enable file time synchronization, set the RestoreFileProperties
to true.
When a transfer is interrupted due to a disconnected connection or user abortion, files that are still in transfer progress may be incomplete. Instead of transferring them all again, you can resume transferring the missing parts of the incomplete files only. By specifying FileOverwriteMode.ResumeFileTransfer
as the action on existing files, the Upload and Download methods can do this automatically. The library will do the following:
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
// Resume upload files.
client.Upload(@"c:\data", "/data", true, FileOverwriteMode.ResumeFileTransfer);
// Resume download "*.dat" and "*.txt" files.
client.Download("/data/*.dat;*.txt", @"c:\data", true, FileOverwriteMode.ResumeFileTransfer, SymlinksResolveAction.Skip);
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
' Resume upload files.
client.Upload("c:\data", "/data", True, FileOverwriteMode.ResumeFileTransfer)
' Resume download "*.dat" and "*.txt" files.
client.Download("/data/*.dat;*.txt", "c:\data", True, FileOverwriteMode.ResumeFileTransfer, SymlinksResolveAction.Skip)
End Using
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// Download "data" directory from the server.
// The local dir "c:\temp" will contain "data" folder
client.Download("/data/", @"c:\temp");
}
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' Download "data" directory from the server.
' The local dir "c:\temp" will contain "data" folder
client.Download("/data/", "c:\temp")
End Using
To download an entire remote directory, pass the path to the directory ending with '/
' to the Download
method.
To upload an entire directory, pass the path to the directory ending with '\
' to the Upload
method.
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// Upload "data" directory to the server.
// The remote dir "/" will contain "/data" folder
client.Upload(@"c:\data\", "/");
}
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' Upload "data" directory to the server.
' The remote dir "/" will contain "/data" folder
client.Upload("c:\data\", "/")
End Using
using (Sftp client = new Sftp())
{
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
FileInfoBase masterFolder = client.CreateFileInfo("/myfolder", false);
FileInfoBase targetFolder1 = DiskFileSystem.Default.CreateFileInfo(@"C:\temp\folder1", false);
FileInfoBase targetFolder2 = DiskFileSystem.Default.CreateFileInfo(@"C:\temp\folder2", false);
Synchronizer sync = new Synchronizer();
SyncOptions opt = new SyncOptions();
opt.AutoConflictResolution = true;
opt.AllowCreations = true;
opt.AllowDeletions = false; // Dont allow deletions.
opt.TimeResolution = TimeResolution.Seconds;
// Set the Time zone offset between the SFTP server and the client
// Let assume that the time offset is 12 hours.
// or you can call client.GetServerTimeDifference() to get the time difference.
client.ServerTimeZoneOffset = new TimeSpan(0, 12, 0, 0);
// Synchronize directories.
sync.Synchronize(masterFolder, opt, null, masterFolder, targetFolder1, targetFolder2);
}
Using client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
Dim masterFolder As FileInfoBase = client.CreateFileInfo("/myfolder", False)
Dim targetFolder1 As FileInfoBase = DiskFileSystem.Default.CreateFileInfo("C:\temp\folder1", False)
Dim targetFolder2 As FileInfoBase = DiskFileSystem.Default.CreateFileInfo("C:\temp\folder2", False)
Dim sync As New Synchronizer()
Dim opt As New SyncOptions()
opt.AutoConflictResolution = True
opt.AllowCreations = True
opt.AllowDeletions = False ' Dont allow deletions.
opt.TimeResolution = TimeResolution.Seconds
' Set the Time zone offset between the SFTP server and the client
' Let assume that the time offset is 12 hours.
' or you can call client.GetServerTimeDifference() to get the time difference.
client.ServerTimeZoneOffset = New TimeSpan(0, 12, 0, 0)
' Synchronize directories.
sync.Synchronize(masterFolder, opt, Nothing, masterFolder, targetFolder1, targetFolder2)
End Using
To synchronize directories, you can follow the steps below:
Synchronizer
classSynchronize
methodThe following example demonstrates how to synchronize directories on an SFTP server with the local directories. Files within the directories will be synchronized with the most recent version of the correspondingly named file.
In addition to supporting standard file transfer methods, the Ultimate SFTP component also offers a set of easy-to-use methods to mirror folders. To mirror a local folder with a remote folder, call the QuickSynchronize
method of the Ftp.
The following steps show you how to use the QuickSynchronize
method to synchronize a remote folder with a local folder.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver", 21);
// Authenticate.
client.Authenticate("userName", "password");
// Create a new instance of the QuickSyncOptions class.
QuickSyncOptions opt = new QuickSyncOptions();
// Set synchronization's settings
opt.Comparer = FileComparers.FileContentComparer;
opt.Recursive = true;
// Synchronize folders.
client.QuickSynchronize(
"/", // Source directory.
"c:\\test", // Destination directory. This local dir will be identical to the remote dir ('/').
true, // Remote dir is master
opt
);
// Do something here
// ...
client.Disconnect();
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver", 21)
' Authenticate.
client.Authenticate("userName", "password")
' Create a new instance of the QuickSyncOptions class.
Dim opt As New QuickSyncOptions()
' Set synchronization's settings
opt.Comparer = FileComparers.FileContentComparer
opt.Recursive = True
' Synchronize folders.
client.QuickSynchronize("/", "c:\test", True, opt) ' Remote dir is master - Destination directory. This local dir will be identical to the remote dir ('/'). - Source directory.
' Do something here
' ...
client.Disconnect()
public void DoAbort()
{
// Create a new Sftp instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
// Upload file "c:\test.zip".
client.UploadFile("c:\\test.zip", "test.zip");
}
catch (SftpException exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, FileSystemProgressEventArgs e)
{
// Abort the uploading operation if the bytes transferred is greater than or equal to 500Kb.
if (e.State == TransferState.Uploading && e.BytesTransferred >= 1024 * 500)
{
((Sftp)sender).Cancel();
}
}
Public Sub DoAbort()
' Create a new Sftp instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
' Upload file "c:\test.zip".
client.UploadFile("c:\test.zip", "test.zip")
Catch exc As SftpException
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As FileSystemProgressEventArgs)
' Abort the uploading operation if the bytes transferred is greater than or equal to 500Kb.
If e.State = TransferState.Uploading AndAlso e.BytesTransferred >= 1024 * 500 Then
CType(sender, Sftp).Cancel()
End If
End Sub
To abort a file transfer that is still in progress, you can either call the Cancel
method or close the connection by calling the Disconnect
or DisconnectAsync
method.
The following code snippet shows how to use it.
When the file to transfer is big, or the transfer speed is slow, you can let the user know that your app is transferring files by updating a progress bar. The Ultimate SFTP component provides progress notification through the Progress event. The event is raised periodically while data transfer is in progress, making accessible necessary data to display progress information, such as the size of the file and the number of bytes transferred.
The following example shows you how to handle the Progress
event to show progress information while transferring a file:
static void Main()
{
// Create a new Sftp instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Authenticate.
client.Authenticate("test", "test");
// Register an event handler.
client.Progress += client_Progress;
// Upload file "c:\test.zip".
client.UploadFile("c:\\test.zip", "test.zip");
// And download file "test.zip".
client.DownloadFile("test.zip", "test_download.zip");
// Disconnect.
client.Disconnect();
}
static void client_Progress(object sender, FileSystemProgressEventArgs e)
{
if (e.State == TransferState.Uploading)
Console.Write("\rUploaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.DestinationPath);
else if (e.State == TransferState.Downloading)
Console.Write("\rDownloaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.SourcePath);
}
Shared Sub Main()
' Create a new Sftp instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Authenticate.
client.Authenticate("test", "test")
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
' Upload file "c:\test.zip".
client.UploadFile("c:\test.zip", "test.zip")
' And download file "test.zip".
client.DownloadFile("test.zip", "test_download.zip")
' Disconnect.
client.Disconnect()
End Sub
Private Shared Sub client_Progress(ByVal sender As Object, ByVal e As FileSystemProgressEventArgs)
If e.State = TransferState.Uploading Then
Console.Write(vbCr & "Uploaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.DestinationPath)
ElseIf e.State = TransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.SourcePath)
End If
End Sub
This section shows how to manage multiple remote files and directories like deleting, moving, and setting permissions.
To delete multiple files, use the Delete
. The methods require the path to the remote directory containing entries to delete as the first parameter. The following illustrates how to use the Delete
to delete multiple files.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Delete all files in folder /my folder.
client.Delete("/my folder", true, true, null);
// Delete all *.tmp files recursively.
client.Delete("/temp", true, true, new NameSearchCondition("*.tmp"));
// Delete selected files only.
object[] filesToDelete = { "/temp/test.cs", "/test/test.tmp" };
client.Delete(filesToDelete, true, true, null);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Delete all files in folder /my folder.
client.Delete("/my folder", True, True, Nothing)
' Delete all *.tmp files recursively.
client.Delete("/temp", True, True, New NameSearchCondition("*.tmp"))
' Delete selected files only.
Dim filesToDelete() As Object = { "/temp/test.cs", "/test/test.tmp" }
client.Delete(filesToDelete, True, True, Nothing)
' ...
' Disconnect.
client.Disconnect()
static void Main()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SSFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Move an entire directory with the standard rename command.
client.Rename("/my old folder", "/my new folder/new one");
TransferOptions opt = new TransferOptions(
true, // Build directory structure.
true, // Recursive.
OptionValue.Yes, // Create empty directories.
(SearchCondition)null, //
FileOverwriteMode.Overwrite,
SymlinksResolveAction.Skip);
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);
// Move the selected files in '/my folder' to 'my new folder'.
string[] files = { "my file1.dat", "file2.txt", "my dir" };
client.Move("/my folder", files, "my new folder", opt);
// Handle file existence event
client.TransferConfirm += client_TransferConfirm;
opt.FileOverwriteMode = FileOverwriteMode.Confirm;
// Move all *.dat and *.txt files to 'my dest' folder.
// If a .txt file already exists, skip it; otherwise overwrite. See the event handler client_TransferConfirm.
client.Move("my source/*.dat,*.txt", "my dest", opt);
// With advanced search conditions.
opt.SearchCondition =
SearchCondition.SizeInRange(10, 10240) + // Search for files with size from 10 -> 10240 bytes
SearchCondition.ModifiedAfter(new DateTime(2010, 05, 01)); // and modifed after 2010/05/01.
// Move XLS files.
client.Move("my data/*.xls", "my dest", opt);
// Move files simultaneously using 3 threads.
client.Move("/my root/*.txt", "/new folder", 3, true);
// ...
// Disconnect.
client.Disconnect();
}
static void client_TransferConfirm(object sender, TransferConfirmEventArgs e)
{
if (e.ConfirmReason == TransferConfirmReason.FileAlreadyExists)
{
if (e.SourceFileInfo.Name.EndsWith(".txt"))
e.NextAction = TransferConfirmNextActions.Skip; // Skip 'txt' file if it already exists.
else
e.NextAction = TransferConfirmNextActions.Overwrite; // otherwise overwrite it.
}
}
Shared Sub Main()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SSFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Move an entire directory with the standard rename command.
client.Rename("/my old folder", "/my new folder/new one")
Dim opt As New TransferOptions(True, True, OptionValue.Yes, CType(Nothing, SearchCondition), FileOverwriteMode.Overwrite, SymlinksResolveAction.Skip) ' Create empty directories. - Recursive. - Build directory structure.
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)
' Move the selected files in '/my folder' to 'my new folder'.
Dim files() As String = { "my file1.dat", "file2.txt", "my dir" }
client.Move("/my folder", files, "my new folder", opt)
' Handle file existence event
AddHandler client.TransferConfirm, AddressOf client_TransferConfirm
opt.FileOverwriteMode = FileOverwriteMode.Confirm
' Move all *.dat and *.txt files to 'my dest' folder.
' If a .txt file already exists, skip it; otherwise overwrite. See the event handler client_TransferConfirm.
client.Move("my source/*.dat,*.txt", "my dest", opt)
' With advanced search conditions.
opt.SearchCondition = SearchCondition.SizeInRange(10, 10240) + SearchCondition.ModifiedAfter(New Date(2010, 05, 01)) ' and modifed after 2010/05/01. - Search for files with size from 10 -> 10240 bytes
' Move XLS files.
client.Move("my data/*.xls", "my dest", opt)
' Move files simultaneously using 3 threads.
client.Move("/my root/*.txt", "/new folder", 3, True)
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Shared Sub client_TransferConfirm(ByVal sender As Object, ByVal e As TransferConfirmEventArgs)
If e.ConfirmReason = TransferConfirmReason.FileAlreadyExists Then
If e.SourceFileInfo.Name.EndsWith(".txt") Then
e.NextAction = TransferConfirmNextActions.Skip ' Skip 'txt' file if it already exists.
Else
e.NextAction = TransferConfirmNextActions.Overwrite ' otherwise overwrite it.
End If
End If
End Sub
To move remote files and directories from one remote directory to another remote directory, use the Move
methods. These methods require the path to the remote directory containing files and directories to move and the path of the destination remote directory. There are many advanced options such as moving files and directories recursively, custom search conditions, and custom file comparison.
The Progress
event of the Sftp
class gives you the ease of controlling files to delete. To decide whether a file should be deleted, just handle the Progress event and set the Skip
property of the FileSystemProgressEventArgs
class to true. The following example illustrates how to do that:
public void DoDelete()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("192.168.126.128", 2222);
// Authenticate.
client.Authenticate("test", "test");
client.Progress += client_Progress;
// ...
// Delete *.tmp files
client.Delete("/", true, "*.tmp");
// ...
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, ComponentPro.IO.FileSystemProgressEventArgs e)
{
if (e.State == TransferState.DeletingFile)
{
// Skip file that its name contains "my file" text.
if (e.SourcePath.IndexOf("my file") != -1)
e.Skip = true;
}
}
Public Sub DoDelete()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("192.168.126.128", 2222)
' Authenticate.
client.Authenticate("test", "test")
AddHandler client.Progress, AddressOf client_Progress
' ...
' Delete *.tmp files
client.Delete("/", True, "*.tmp")
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As ComponentPro.IO.FileSystemProgressEventArgs)
If e.State = TransferState.DeletingFile Then
' Skip file that its name contains "my file" text.
If e.SourcePath.IndexOf("my file") <> -1 Then
e.Skip = True
End If
End If
End Sub
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Create a new attribute object and set permissions and modifed date time.
SftpFileAttributes attrs = new SftpFileAttributes();
attrs.Permissions = SftpFilePermissions.OwnerExecute | SftpFilePermissions.OwnerWrite |
SftpFilePermissions.OwnerRead;
attrs.LastWriteTime = DateTime.Now;
// Set all files.
client.SetMultipleFilesAttributes("/my folder", attrs, true, null);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Create a new attribute object and set permissions and modifed date time.
Dim attrs As New SftpFileAttributes()
attrs.Permissions = SftpFilePermissions.OwnerExecute Or SftpFilePermissions.OwnerWrite Or SftpFilePermissions.OwnerRead
attrs.LastWriteTime = Date.Now
' Set all files.
client.SetMultipleFilesAttributes("/my folder", attrs, True, Nothing)
' ...
' Disconnect.
client.Disconnect()
Ultimate SFTP provides both methods for setting attributes of a single file or multiple files. To set attributes of multiple files, use the SetMultipleFilesAttributes method of the Sftp class. The following example shows you how easy it is to set attributes of multiple files.
To understand more about wildcard masks and search criterion, see this topic.
In addition to supporting standard file transfer methods, the Ultimate SFTP component also offers a set of easy-to-use methods to manage remote directories: list folder content, create, rename/move, check existence, delete recursively, and get folder total size.
Use the ListDirectory
method of Sftp
to read the directory contents. The first parameter of that method is the path to the directory. The resulting list returned by the ListDirectory
method contains references to instances of FtpFileInfo
class. Each instance contains information about a directory entry (file, subdirectory, symlink etc.)
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get information of all files and directories in '/' remote dir.
foreach (SftpFileInfo info in client.ListDirectory("/"))
{
Console.WriteLine("Name: {0}, UserId: {1}, Permissions: {2}, Size: {3}", info.Name, info.OwnerId, info.Permissions, info.Length);
}
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get information of all files and directories in '/' remote dir.
For Each info As SftpFileInfo In client.ListDirectory("/")
Console.WriteLine("Name: {0}, UserId: {1}, Permissions: {2}, Size: {3}", info.Name, info.OwnerId, info.Permissions, info.Length)
Next info
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get the current directory.
string absolutePath = client.GetCurrentDirectory();
Console.WriteLine("Current directory is '{0}'", absolutePath);
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get the current directory.
Dim absolutePath As String = client.GetCurrentDirectory()
Console.WriteLine("Current directory is '{0}'", absolutePath)
' ...
' Disconnect.
client.Disconnect()
To get the current working directory for the currently logged in user, use GetCurrentDirectory
method. To change it, use SetCurrentDirectory
method.
To create a new directory, call the CreateDirectory
method of the Sftp
class. By default, a new directory will be created in the current working directory. If you want to create the directory in another location, you could use the SetCurrentDirectory
to change the current working directory before calling the CreateDirectory method. The method also accepts an absolute path.
The following code example shows you how to use the CreateDirectory
method to create a new directory on the remote SFTP server.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Create 'myFolder' directory.
client.CreateDirectory("/myFolder");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Create 'myFolder' directory.
client.CreateDirectory("/myFolder")
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SSFTP server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
client.EnsuresDirectoryCreated("/home/data/personal/photos/family-photos");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SSFTP server.
client.Connect("server")
' Authenticate.
client.Authenticate("test", "test")
client.EnsuresDirectoryCreated("/home/data/personal/photos/family-photos")
' ...
' Disconnect.
client.Disconnect()
When you need to create a directory with path like "/home/data/personal/photos/family-photos", but you are not sure whether "/home/data", "/home/data/personal", or "/home/data/personal/photos" exists. You may end up splitting the path by '/' character and checking the split paths for existence one by one. The FileSystem
base class from which the Sftp class inherit has a method EnsuresDirectoryCreated
method to help you do so.
To rename a directory, use the Rename
method. It also supports moving a remote directory to another location.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Rename remote file '/file.dat' to 'myfile.dat'
client.Rename("/file.dat", "/myfile.dat");
// Move a file
client.Rename("/file2.dat", "/new-folder/file2.dat");
// Rename a remote directory
client.Rename("/album-folder", "/old-album-folder");
// Move a directory
client.Rename("/album-folder2", "/new-folder/album-folder2");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Rename remote file '/file.dat' to 'myfile.dat'
client.Rename("/file.dat", "/myfile.dat")
' Move a file
client.Rename("/file2.dat", "/new-folder/file2.dat")
' Rename a remote directory
client.Rename("/album-folder", "/old-album-folder")
' Move a directory
client.Rename("/album-folder2", "/new-folder/album-folder2")
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Determine whether folder 'myFolder' exists or not.
if (client.DirectoryExists("/myFolder"))
Console.WriteLine("Folder '/myFolder' exists");
else
Console.WriteLine("Folder '/myFolder' does not exist");
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Determine whether folder 'myFolder' exists or not.
If client.DirectoryExists("/myFolder") Then
Console.WriteLine("Folder '/myFolder' exists")
Else
Console.WriteLine("Folder '/myFolder' does not exist")
End If
' ...
' Disconnect.
client.Disconnect()
To determine whether a remote directory exists or not, use the DirectoryExists
method. You just need to pass the path of the remote directory to the method, and it returns a boolean value indicating whether the specified directory exists or not.
The following code snippet shows you how to use the DirectoryExists
method to determine whether a directory exists or not.
To delete a non-empty remote directory or multiple files, use the Delete
method. If the recursive parameter of the method is passed as true, the method searches for entries in subdirectories as well. Hence, you should use the method with attention.
To delete an empty directory, use the DeleteDirectory
method.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Remove an empty directory.
client.DeleteDirectory("/temp");
// Delete an entire directory.
client.DeleteDirectory("/test", true);
// Delete files with size smaller than 200kb in "/test dir" directory. All empty directories will be removed.
client.Delete("/my folder", true, new SizeSearchCondition(0, 200 * 1024));
// Delete .exe files in "/test dir" directory. All empty directories will be removed.
client.Delete("/test dir", true, "*.exe");
// Delete .tmp and .temp files in "/test dir" directory. All empty directories will be removed.
// wildcard masks are delimited by ';', ',', and '|' characters.
client.Delete("/test dir/*.tmp;*.temp", true);
// Delete .cs files in "/test folder" directory. All empty directories are not to be removed.
client.Delete("/test folder", true, false, new NameSearchCondition(".cs"));
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Remove an empty directory.
client.DeleteDirectory("/temp")
' Delete an entire directory.
client.DeleteDirectory("/test", True)
' Delete files with size smaller than 200kb in "/test dir" directory. All empty directories will be removed.
client.Delete("/my folder", True, New SizeSearchCondition(0, 200 * 1024))
' Delete .exe files in "/test dir" directory. All empty directories will be removed.
client.Delete("/test dir", True, "*.exe")
' Delete .tmp and .temp files in "/test dir" directory. All empty directories will be removed.
' wildcard masks are delimited by ';', ',', and '|' characters.
client.Delete("/test dir/*.tmp;*.temp", True)
' Delete .cs files in "/test folder" directory. All empty directories are not to be removed.
client.Delete("/test folder", True, False, New NameSearchCondition(".cs"))
' ...
' Disconnect.
client.Disconnect()
void CalculateDirSize()
{
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Calculate total size of an entire directory.
long totalSize = client.GetDirectorySize("/myFolder", true, null);
Console.WriteLine("Calculate total size for all files: " + FormatSize(totalSize));
// Calculate total size for files with extension .dat.
totalSize = client.GetDirectorySize("/myFolder", true, "*.dat");
Console.WriteLine("Calculate total size for all .dat files: " + FormatSize(totalSize));
// Calculate total size for files that are bigger than 100kb.
totalSize = client.GetDirectorySize("/myFolder", true, new SizeSearchCondition(100 * 1024, long.MaxValue));
Console.WriteLine("Total size: " + FormatSize(totalSize));
// ...
// Disconnect.
client.Disconnect();
}
/// <summary>
/// Returns a formatted file size in bytes, kbytes, or mbytes.
/// </summary>
/// <param name="size">The input file size.</param>
/// <returns>The formatted file size.</returns>
public string FormatSize(long size)
{
if (size < 1024)
return size + " B";
if (size < 1024 * 1024)
return string.Format("{0:#.#} KB", size / 1024.0f);
return size < 1024 * 1024 * 1024 ? string.Format("{0:#.#} MB", size / 1024.0f / 1024.0f) : string.Format("{0:#.#} GB", size / 1024.0f / 1024.0f / 1024.0f);
}
Private Sub CalculateDirSize()
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Calculate total size of an entire directory.
Dim totalSize As Long = client.GetDirectorySize("/myFolder", True, Nothing)
Console.WriteLine("Calculate total size for all files: " & FormatSize(totalSize))
' Calculate total size for files with extension .dat.
totalSize = client.GetDirectorySize("/myFolder", True, "*.dat")
Console.WriteLine("Calculate total size for all .dat files: " & FormatSize(totalSize))
' Calculate total size for files that are bigger than 100kb.
totalSize = client.GetDirectorySize("/myFolder", True, New SizeSearchCondition(100 * 1024, Long.MaxValue))
Console.WriteLine("Total size: " & FormatSize(totalSize))
' ...
' Disconnect.
client.Disconnect()
End Sub
''' <summary>
''' Returns a formatted file size in bytes, kbytes, or mbytes.
''' </summary>
''' <param name="size">The input file size.</param>
''' <returns>The formatted file size.</returns>
Public Function FormatSize(ByVal size As Long) As String
If size < 1024 Then
Return size & " B"
End If
If size < 1024 * 1024 Then
Return String.Format("{0:#.#} KB", size / 1024.0F)
End If
If size < 1024 * 1024 * 1024 Then
Return String.Format("{0:#.#} MB", size / 1024.0F / 1024.0F)
Else
Return String.Format("{0:#.#} GB", size / 1024.0F / 1024.0F / 1024.0F)
End If
End Function
Use the GetDirectorySize
method to calculate the total content size of a directory on the SFTP server. The Sftp
class automatically does all the hard work such as detecting SFTP Server OS, determining the listing type, listing directories, and calculating the total content size.
The following steps show you how to use the GetDirectorySize
method to retrieve the total content size of a remote directory in bytes.
You can use the MaxUploadSpeed
and MaxDownloadSpeed
properties to limit the transfer speed of the Sftp
class. The class also let you choose optimum option to improve transfer speed. In some cases, setting the Ftp.Config.HighSpeedNetworkOptimization
property to true may improve the transfer speed, particularly when downloading. If the property is set to true, TCP socket's receive buffer is set to 4MB, and TCP socket's send buffer is set to 256KB.
ComponentPro transport classes (Ftp and Sftp) support so-called bandwidth control - restrictions on the amount of data transferred per second. Bandwidth throttlings are set separately for uploading and downloading data. There are some reasons why an application needs the bandwidth throttling feature.
When the network connection is shared between multiple consumers, high transfer speed is not always desirable. In this situation, it is essential for the application using the component not to consume too much network bandwidth and let other consumers make use of the network as well.
In slow and unstable networks, lower speed of transfer usually increases stability and decreases the chance of network failure and disconnection.
MaxUploadSpeed
and MaxDownloadSpeed
properties of the Sftp
component can be used to adjust transfer speed on the fly.
// Limit max download speed to 10k (1024 * 10 bytes) per second.
client.MaxDownloadSpeed = 10 * 1024;
// Limit max upload speed to 8k (1024 * 8 bytes) per second.
client.MaxDownloadSpeed = 8 * 1024;
' Limit max download speed to 10k (1024 * 10 bytes) per second.
client.MaxDownloadSpeed = 10 * 1024
' Limit max upload speed to 8k (1024 * 8 bytes) per second.
client.MaxDownloadSpeed = 8 * 1024
You can handle the events in the Sftp
class to control file transfer and get notified when an event is triggered by the Sftp
class.
The Banner
event is triggered after a banner message has been received from the SFTP server. By handling this event, you can display the welcome message received from the SFTP server.
public void HandleBannerEvent()
{
// Create a new class instance.
Sftp client = new Sftp();
// Register an event handler.
client.Banner += client_Banner;
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
// Disconnect.
client.Disconnect();
}
void client_Banner(object sender, BannerEventArgs e)
{
// Print out the message.
Console.WriteLine(e.Banner);
}
Public Sub HandleBannerEvent()
' Create a new class instance.
Dim client As New Sftp()
' Register an event handler.
AddHandler client.Banner, AddressOf client_Banner
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Banner(ByVal sender As Object, ByVal e As BannerEventArgs)
' Print out the message.
Console.WriteLine(e.Banner)
End Sub
public void HandleHostKeyVerifyingEvent()
{
// Create a new class instance.
Sftp client = new Sftp();
client.HostKeyVerifying += client_HostKeyVerifying;
// Connect to the SFTP server.
client.Connect("myserver");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
void client_HostKeyVerifying(object sender, HostKeyVerifyingEventArgs e)
{
// Print out the fingerprint info.
Console.Write(string.Format("Host key: {0}. Do you want to accept this host key?(y/n):", e.HostKey.ToString()));
string answer = Console.ReadLine();
// Accept the fingerprint if user entered "y".
e.Accept = answer.ToLower() == "y";
}
Public Sub HandleHostKeyVerifyingEvent()
' Create a new class instance.
Dim client As New Sftp()
AddHandler client.HostKeyVerifying, AddressOf client_HostKeyVerifying
' Connect to the SFTP server.
client.Connect("myserver")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_HostKeyVerifying(ByVal sender As Object, ByVal e As HostKeyVerifyingEventArgs)
' Print out the fingerprint info.
Console.Write(String.Format("Host key: {0}. Do you want to accept this host key?(y/n):", e.HostKey.ToString()))
Dim answer As String = Console.ReadLine()
' Accept the fingerprint if user entered "y".
e.Accept = answer.ToLower() = "y"
End Sub
The HostKeyVerifying event is triggered after a fingerprint has been received from the server and needs to be validated. By handling this event, you can continue connecting to the SFTP or cancel and close the connection.
The following steps guide you on how to handle this event.
The PasswordChangeRequest event is triggered when user's password need to be changed. By handling this event, you can change the password if the system request. It usually happens when the old password has expired.
public void HandleEvent()
{
// Create a new class instance.
Sftp client = new Sftp();
client.PasswordChangeRequest += client_PasswordChangeRequest;
// Connect to the SFTP server.
client.Connect("myserver");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
void client_PasswordChangeRequest(object sender, PasswordChangeRequestEventArgs e)
{
Console.WriteLine(e.Prompt);
Console.Write("Please enter new password: ");
// Set new password. This is needed when the system requests user to change his password when it is expired.
e.NewPassword = Console.ReadLine();
}
Public Sub HandleEvent()
' Create a new class instance.
Dim client As New Sftp()
AddHandler client.PasswordChangeRequest, AddressOf client_PasswordChangeRequest
' Connect to the SFTP server.
client.Connect("myserver")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_PasswordChangeRequest(ByVal sender As Object, ByVal e As PasswordChangeRequestEventArgs)
Console.WriteLine(e.Prompt)
Console.Write("Please enter new password: ")
' Set new password. This is needed when the system requests user to change his password when it is expired.
e.NewPassword = Console.ReadLine()
End Sub
public void HandleListItemReceived()
{
// Create a new class instance.
Sftp client = new Sftp();
client.ListItemReceived += client_ListItemReceived;
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Or you can specify the SFTP port with
// client.Connect("myserver", 22);
// Authenticate.
client.Authenticate("test", "test");
// ...
// Get file list in the currently working directory.
client.ListDirectory();
// ...
// Disconnect.
client.Disconnect();
}
void client_ListItemReceived(object sender, SftpListItemReceivedEventArgs e)
{
// Skip files with size < 1k
if (e.File.IsFile && e.File.Length < 1024)
e.Skip = true;
else
{
// Display the item
Console.WriteLine("Received raw line: " + e.RawLine);
Console.WriteLine("SFTP file: " + e.File.ToString());
}
}
Public Sub HandleListItemReceived()
' Create a new class instance.
Dim client As New Sftp()
AddHandler client.ListItemReceived, AddressOf client_ListItemReceived
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Or you can specify the SFTP port with
' client.Connect("myserver", 22);
' Authenticate.
client.Authenticate("test", "test")
' ...
' Get file list in the currently working directory.
client.ListDirectory()
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_ListItemReceived(ByVal sender As Object, ByVal e As SftpListItemReceivedEventArgs)
' Skip files with size < 1k
If e.File.IsFile AndAlso e.File.Length < 1024 Then
e.Skip = True
Else
' Display the item
Console.WriteLine("Received raw line: " & e.RawLine)
Console.WriteLine("SFTP file: " & e.File.ToString())
End If
End Sub
ListItemReceived
event is triggered when a file and directory listing item has been received by ListDirectory
, ListRawName
or ListName
methods. By handling this event, you can display information of the received SFTP item or even parse the raw data of the received item line.
The following steps guide you on how to handle this event.
Progress
event is triggered when a block of data has been sent or received. By handling this event, you can display transfer progress information, source file name, destination file name, etc.
static void Main()
{
// Create a new Sftp instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Authenticate.
client.Authenticate("test", "test");
// Register an event handler.
client.Progress += client_Progress;
// Upload file "c:\test.zip".
client.UploadFile("c:\\test.zip", "test.zip");
// And download file "test.zip".
client.DownloadFile("test.zip", "test_download.zip");
// Disconnect.
client.Disconnect();
}
static void client_Progress(object sender, FileSystemProgressEventArgs e)
{
if (e.State == TransferState.Uploading)
Console.Write("\rUploaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.DestinationPath);
else if (e.State == TransferState.Downloading)
Console.Write("\rDownloaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.SourcePath);
}
Shared Sub Main()
' Create a new Sftp instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Authenticate.
client.Authenticate("test", "test")
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
' Upload file "c:\test.zip".
client.UploadFile("c:\test.zip", "test.zip")
' And download file "test.zip".
client.DownloadFile("test.zip", "test_download.zip")
' Disconnect.
client.Disconnect()
End Sub
Private Shared Sub client_Progress(ByVal sender As Object, ByVal e As FileSystemProgressEventArgs)
If e.State = TransferState.Uploading Then
Console.Write(vbCr & "Uploaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.DestinationPath)
ElseIf e.State = TransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed) - {2}", e.BytesTransferred, e.Percentage, e.SourcePath)
End If
End Sub
public static void Main()
{
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName, serverPort);
// Authenticate the user
client.Authenticate(userName, password);
client.TransferConfirm += ClientOnTransferConfirm;
// Download all files from "/data" to "d:\temp".
client.Download("/data", @"d:\temp", true, FileOverwriteMode.Confirm, SymlinksResolveAction.Skip);
}
}
private static void ClientOnTransferConfirm(object sender, TransferConfirmEventArgs e)
{
// If the reason is "File already exists"
if (e.ConfirmReason == TransferConfirmReason.FileAlreadyExists)
{
string oldName = e.DestinationFileInfo.Name;
int n = oldName.LastIndexOf('.');
string ext = n != -1 ? oldName.Substring(n) : null;
string name = n != -1 ? oldName.Substring(0, n) : oldName;
// Append "(1)" to the file name
e.NewName = name + "(1)" + ext;
e.NextAction = TransferConfirmNextActions.Rename;
}
}
Public Shared Sub Main()
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName, serverPort)
' Authenticate the user
client.Authenticate(userName, password)
AddHandler client.TransferConfirm, AddressOf ClientOnTransferConfirm
' Download all files from "/data" to "d:\temp".
client.Download("/data", "d:\temp", True, FileOverwriteMode.Confirm, SymlinksResolveAction.Skip)
End Using
End Sub
Private Shared Sub ClientOnTransferConfirm(ByVal sender As Object, ByVal e As TransferConfirmEventArgs)
' If the reason is "File already exists"
If e.ConfirmReason = TransferConfirmReason.FileAlreadyExists Then
Dim oldName As String = e.DestinationFileInfo.Name
Dim n As Integer = oldName.LastIndexOf("."c)
Dim ext As String
If n <> -1 Then
ext = oldName.Substring(n)
Else
ext = Nothing
End If
Dim name As String
If n <> -1 Then
name = oldName.Substring(0, n)
Else
name = oldName
End If
' Append "(1)" to the file name
e.NewName = name & "(1)" & ext
e.NextAction = TransferConfirmNextActions.Rename
End If
End Sub
When transferring lots of files using the Upload
or Download
methods, things can occasionally go wrong due to unpredictable problems. Those issues may be:
To be informed about such errors, handle the TransferConfirm
event. In the handler of that event, you can choose how to react to the issue by setting the TransferConfirmEventArgs.NextAction
property. The TransferConfirmEventArgs data object of the TransferConfirm event has lots of useful members to help you know what the issue is, what the source and destination files are and what the reaction should be.
The following code snippet demonstrates how to handle the TransferConfirm
event to append "(1)" phrase to the file name of an existing target file.
The CommandResponse
event is triggered when a command has been sent to the SFTP server or when Ultimate SFTP component has received a response from the server. This event is commonly used to add trace log capabilities to your applications. For more details on how to handle this event, visit Making a trace log using events. There is still another convenient way to add log capabilities to your application is using the XTrace class.
public void HandleCommandSentResponseReadEvents()
{
// Create a new class instance.
Sftp client = new Sftp();
// Register event handlers.
client.CommandResponse += client_CommandResponse;
// Connect to the SFTP server.
client.Connect("demo.componentpro.com");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
client.UploadFile("c:\\test.dat", "/test.dat");
// ...
// Disconnect.
client.Disconnect();
}
void client_CommandResponse(object sender, CommandResponseEventArgs e)
{
if (e.Command != null)
Console.WriteLine("CMD> " + e.Command);
else
Console.WriteLine("RESPONSE> " + e.Response);
}
Public Sub HandleCommandSentResponseReadEvents()
' Create a new class instance.
Dim client As New Sftp()
' Register event handlers.
AddHandler client.CommandResponse, AddressOf client_CommandResponse
' Connect to the SFTP server.
client.Connect("demo.componentpro.com")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
client.UploadFile("c:\test.dat", "/test.dat")
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_CommandResponse(ByVal sender As Object, ByVal e As CommandResponseEventArgs)
If e.Command IsNot Nothing Then
Console.WriteLine("CMD> " & e.Command)
Else
Console.WriteLine("RESPONSE> " & e.Response)
End If
End Sub
public void HandleStateChangedEvent()
{
// Create a new class instance.
Sftp client = new Sftp();
client.StateChanged += client_StateChanged;
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
// Disconnect.
client.Disconnect();
}
void client_StateChanged(object sender, RemoteFileSystemStateChangedEventArgs e)
{
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.State);
}
Public Sub HandleStateChangedEvent()
' Create a new class instance.
Dim client As New Sftp()
AddHandler client.StateChanged, AddressOf client_StateChanged
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_StateChanged(ByVal sender As Object, ByVal e As RemoteFileSystemStateChangedEventArgs)
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.State)
End Sub
The StateChanged
event is triggered when the state of the Sftp
object has been changed. By handling this event, you will get notification when a connection has been established or the connection has been lost.
The following steps guide you on how to handle this event.
The library also comes with some advanced features below:
FTP and SFTP are two different file transfer protocols, but they both cover same task - transferring files over the network. Our Unified File System library lets you write the same code for file management with FTP, SFTP, and ZIP. One of the benefits of having similar API across Sftp, Ftp, and Zip classes is that the time required to familiarize yourself with a new protocol is minimized or eliminated altogether. The interface IRemoteFileSystem
that both Sftp
and Sftp
classes implement, defines most Sftp and Ftp methods, properties, and events, making it easy to write the single code segment to work with both protocols as shown in the example below:
// The IRemoteFileSystem interface is used for all remote file systems, including Ftp, Sftp, and Scp.
IRemoteFileSystem client;
// Create a new class instance.
if (isFtp)
client = new Ftp();
else
client = new Sftp();
// Connect to the server
client.Connect(serverName, serverPort);
// Authenticate the user.
client.Authenticate(userName, password);
// Upload files in "C:\data" to "/data".
client.Upload(@"C:\data", "/data");
// Download a remote file.
client.DownloadFile("/content/file.txt", @"c:\data\file.txt");
// Close the connection.
client.Disconnect();
' The IRemoteFileSystem interface is used for all remote file systems, including Ftp, Sftp, and Scp.
Dim client As IRemoteFileSystem
' Create a new class instance.
If isFtp Then
client = New Ftp()
Else
client = New Sftp()
End If
' Connect to the server
client.Connect(serverName, serverPort)
' Authenticate the user.
client.Authenticate(userName, password)
' Upload files in "C:\data" to "/data".
client.Upload("C:\data", "/data")
' Download a remote file.
client.DownloadFile("/content/file.txt", "c:\data\file.txt")
' Close the connection.
client.Disconnect()
// Create a new instance of the Sftp class.
using (Sftp client = new Sftp())
{
// Connect to the server.
client.Connect(serverName);
// Authenticate the user
client.Authenticate(userName, password);
// Initialize a queue with 5 threads.
TransferQueue queue = new TransferQueue(5);
// Add items to the queue
queue.Add(DiskFileSystem.Default.CreateFileInfo(@"C:\data\folder1"), client.CreateFileInfo("/data/folder1"), false, null, 0);
queue.Add(DiskFileSystem.Default.CreateFileInfo(@"C:\data\folder2"), client.CreateFileInfo("/data/folder2"), false, null, 0);
queue.Add(DiskFileSystem.Default.CreateFileInfo(@"C:\data\file1"), client.CreateFileInfo("/data/file1"), false, null, 0);
// Start the queue.
// It immediately returns control to the caller's process.
queue.Start(false);
// ...
// Here we can add more items to the queue while it's in progress
queue.Add(DiskFileSystem.Default.CreateFileInfo(@"C:\data\folder3"), client.CreateFileInfo("/data/folder3"), false, null, 0);
// ...
// or we can change the number of threads.
// e.g. use 5 more threads -> 10 threads.
queue.Threads = 10;
// ...
// the queue can be paused.
queue.Stop();
// ...
// and then resumed
queue.Start(true);
// ...
// we can also wait until it completes.
queue.Wait(true);
}
' Create a new instance of the Sftp class.
Using client As New Sftp()
' Connect to the server.
client.Connect(serverName)
' Authenticate the user
client.Authenticate(userName, password)
' Initialize a queue with 5 threads.
Dim queue As New TransferQueue(5)
' Add items to the queue
queue.Add(DiskFileSystem.Default.CreateFileInfo("C:\data\folder1"), client.CreateFileInfo("/data/folder1"), False, Nothing, 0)
queue.Add(DiskFileSystem.Default.CreateFileInfo("C:\data\folder2"), client.CreateFileInfo("/data/folder2"), False, Nothing, 0)
queue.Add(DiskFileSystem.Default.CreateFileInfo("C:\data\file1"), client.CreateFileInfo("/data/file1"), False, Nothing, 0)
' Start the queue.
' It immediately returns control to the caller's process.
queue.Start(False)
' ...
' Here we can add more items to the queue while it's in progress
queue.Add(DiskFileSystem.Default.CreateFileInfo("C:\data\folder3"), client.CreateFileInfo("/data/folder3"), False, Nothing, 0)
' ...
' or we can change the number of threads.
' e.g. use 5 more threads -> 10 threads.
queue.Threads = 10
' ...
' the queue can be paused.
queue.Stop()
' ...
' and then resumed
queue.Start(True)
' ...
' we can also wait until it completes.
queue.Wait(True)
End Using
Are you looking for a component that has the capability to add files and directories to a queue and start, stop or pause the queue any time? The TransferQueue class is designed to do that job. The free LionFTP client is an example of how a WinForms application makes use of that class.
That class also allows you to add files to transfer, sort file list, set item priority on-the-fly. It also lets you change the number of threads used to transfer files while the queue is still in process, start, pause and resume the queue.
To determine the time difference between the client and the SFTP server, call the GetServerTimeDifference
method. We will take advantage of this method with the following example.
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Get the time difference between the server and the client.
TimeSpan ts = client.GetServerTimeDifference();
Console.WriteLine("Time difference: " + ts.ToString());
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Get the time difference between the server and the client.
Dim ts As TimeSpan = client.GetServerTimeDifference()
Console.WriteLine("Time difference: " & ts.ToString())
' ...
' Disconnect.
client.Disconnect()
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("localhost");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Download remote file '/test.dat' to 'c:\test.dat'
long transferred = await client.DownloadFileAsync("/test.dat", "c:\\test.dat");
// ...
Console.WriteLine("Bytes transferred: " + transferred);
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("localhost")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Download remote file '/test.dat' to 'c:\test.dat'
Dim transferred As Long = Await client.DownloadFileAsync("/test.dat", "c:\test.dat")
' ...
Console.WriteLine("Bytes transferred: " & transferred)
' Disconnect.
client.Disconnect()
Sftp
provides a number of methods allowing you to asynchronously connect, login, upload, download, etc. Their names always end with Async. This means the method will begin some operation on a new thread and immediately return to the caller. When the operation has completed, the corresponding event will be raised notifying you that the operation has completed and in the event handler method you can check for the error and use the result, if provided.
The example following demonstrates how to connect to an SFTP server and download a file asynchronously:
The component also offers a number of useful features to communicate with SSH servers:
TCP communication protocols including FTP, HTTP, SCP, SMTP, IMAP, POP3 and Telnet can use SSH as a transport layer. The following example illustrates how to use an SSH session as a proxy for an FTP connection.
// Establish a shared SSH connection
SecureShellConnection session = new SecureShellConnection();
session.Connect(serverName);
session.Authenticate(userName, password);
// Use the established SSH connection as proxy to connect to the FTP server
Ftp ftp = new Ftp();
ftp.SetSocketFactory(session.ToSocketFactory());
ftp.Connect(ftpServerName);
ftp.Authenticate(ftpUserName, ftpPassword);
// Use the ftp object to upload, download, delete files, etc.
// ...
' Establish a shared SSH connection
Dim session As New SecureShellConnection()
session.Connect(serverName)
session.Authenticate(userName, password)
' Use the established SSH connection as proxy to connect to the FTP server
Dim ftp As New Ftp()
ftp.SetSocketFactory(session.ToSocketFactory())
ftp.Connect(ftpServerName)
ftp.Authenticate(ftpUserName, ftpPassword)
' Use the ftp object to upload, download, delete files, etc.
' ...
// Create a new class instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// ...
// Keep the connection alive.
client.KeepAlive();
// ...
// Disconnect.
client.Disconnect();
' Create a new class instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' ...
' Keep the connection alive.
client.KeepAlive()
' ...
' Disconnect.
client.Disconnect()
To prevent some firewall/router devices from dropping inactive connections, the client can send a special packet periodically to the server to keep the connection alive using the KeepAlive method.
Some SSH servers allow changing a user's password programmatically. In the Ultimate SFTP component, you can use the ChangePassword method of the SecureShellConnection class or ChangePassword of the Sftp class to accomplish that.
A user's password can only be changed before authenticating him or her.
static void SftpChangePassword()
{
// Create a new Sftp instance.
Sftp client = new Sftp();
// Connect to the SFTP server.
client.Connect(serverName);
// Change a user's password
SecureShellChangePasswordResult result = client.ChangePassword("test", "oldPass", "newPass");
// Check the result
switch (result)
{
case SecureShellChangePasswordResult.Success:
// The password has been changed
// and the user is also logged on using the new password
break;
case SecureShellChangePasswordResult.ChangedButNotAuthenticated:
// The user's password has been changed
// but user needs to authenticate
client.Authenticate(userName, newPassword);
break;
case SecureShellChangePasswordResult.Failure:
// Failed to change the password
throw new Exception("Password change failed.");
}
// Disconnect.
client.Disconnect();
}
Private Shared Sub SftpChangePassword()
' Create a new Sftp instance.
Dim client As New Sftp()
' Connect to the SFTP server.
client.Connect(serverName)
' Change a user's password
Dim result As SecureShellChangePasswordResult = client.ChangePassword("test", "oldPass", "newPass")
' Check the result
Select Case result
Case SecureShellChangePasswordResult.Success
' The password has been changed
' and the user is also logged on using the new password
Case SecureShellChangePasswordResult.ChangedButNotAuthenticated
' The user's password has been changed
' but user needs to authenticate
client.Authenticate(userName, newPassword)
Case SecureShellChangePasswordResult.Failure
' Failed to change the password
Throw New Exception("Password change failed.")
End Select
' Disconnect.
client.Disconnect()
End Sub
// Create a new instance of the SecureShellConnection class.
SecureShellConnection ssh = new SecureShellConnection();
// Connect to the SSH server.
ssh.Connect(serverName);
// Authenticate
ssh.Authenticate(userName, password);
// Create a new instance of the Sftp class
// and bind it to the ssh connection.
Sftp client = new Sftp();
client.ReuseConnection(ssh);
// Upload a file.
client.UploadFile(@"D:\data\test.dat", "test.dat");
// ...
// An instance of the Scp class can also be bound to the SSH connection
Scp scp = new Scp();
scp.ReuseConnection(ssh);
// ...
// Close the connection
ssh.Disconnect();
' Create a new instance of the SecureShellConnection class.
Dim ssh As New SecureShellConnection()
' Connect to the SSH server.
ssh.Connect(serverName)
' Authenticate
ssh.Authenticate(userName, password)
' Create a new instance of the Sftp class
' and bind it to the ssh connection.
Dim client As New Sftp()
client.ReuseConnection(ssh)
' Upload a file.
client.UploadFile("D:\data\test.dat", "test.dat")
' ...
' An instance of the Scp class can also be bound to the SSH connection
Dim scp As New Scp()
scp.ReuseConnection(ssh)
' ...
' Close the connection
ssh.Disconnect()
An SSH connection can be shared between several Sftp and Scp objects. For example, we create an SSH connection and bind an Sftp and Scp objects to the connection to transfer some files and we run a command over a single connection only.