Downloading files and directories to a ZIP file

To download files and directories on an SFTP server to a ZIP file, you will need to add reference to UltimateZip.dllassembly. The UltimateZip is available for download at: UltimateZip Download Page For more information about this product, visit its home page.

The following example code shows you how to connect to an SFTP server and download files to a ZIP file on-the-fly.

C#:

// Connect to an SFTP file system.
Sftp sftp = new Sftp();
sftp.Connect("componentpro.com", 22);
sftp.Authenticate("test", "test");
// Create a new zip file.
Zip zip = new Zip();
zip.Create("test.zip");
// Add all remote files to the newly created archive.
// This operation directly adds files to the ZIP file, no temporary files created.
// Use this
zip.AddFiles(sftp, "", (IFileInfo[])null, "", new TransferOptions());
// or this
//sftp.DownloadFiles("", (IFileInfo[])null, zip, "", new TransferOptions());
// Close all used resources.
zip.Close();
sftp.Disconnect();

VB.NET:

' Connect to an SFTP file system.
Dim sftp As New Sftp()
sftp.Connect("componentpro.com", 22)
sftp.Authenticate("test", "test")
' Create a new zip file.
Dim zip As New Zip()
zip.Create("test.zip")
' Add all remote files to the newly created archive.
' This operation directly adds files to the ZIP file, no temporary files created.
' Use this
zip.AddFiles(sftp, "", CType(Nothing, IFileInfo()), "", New TransferOptions())
' or this
'sftp.DownloadFiles("", (IFileInfo[])null, zip, "", new TransferOptions());
' Close all used resources.
zip.Close()
sftp.Disconnect()

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

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

C#:

void SFTPandFTPConnection(IRemoteFileSystem client, string host, int port, string username, string password) 
{ 
    // Connect to the server.
    client.Connect(host, port); 
    // Authenticate the user.
    client.Authenticate(username, password); 

    FileSystem system = client as FileSystem; 

    // Delete .tmp files in the current working folder.
    client.DeleteDirectory("", true, "*.tmp"); 

    // Create a new directory 
    client.CreateDirectory("my dir"); 

    // Download files from the root directory. 
    TransferOptions opt = new TransferOptions(); 
    opt.Recursive = RecursionMode.ScanAllSubDirectories;
    FileSystem.TransferFiles(system, "/", (IFileInfo[])null, DiskFileSystem.Default, @"C:\temp", opt); 

    // Upload files from C:\test to the root directory 
    FileSystem.TransferFiles(DiskFileSystem.Default, @"C:\Test", (IFileInfo[])null, system, "/", opt); 

    // Close the connection.
    client.Disconnect(); 
}

VB.NET

Private Sub SFTPandFTPConnection(ByVal client As IRemoteFileSystem, ByVal host As String, ByVal port As Integer, ByVal username As String, ByVal password As String)
    ' Connect to the server.
    client.Connect(host, port)
    ' Authenticate the user.
    client.Authenticate(username, password)

    Dim system As FileSystem = TryCast(client, FileSystem)

    ' Delete .tmp files in the current working folder.
    client.DeleteDirectory("", True, "*.tmp")

    ' Create a new directory 
    client.CreateDirectory("my dir")

    ' Download files from the root directory. 
    Dim opt As New TransferOptions()
    opt.Recursive = RecursionMode.ScanAllSubDirectories
    FileSystem.TransferFiles(system, "/", CType(Nothing, IFileInfo()), DiskFileSystem.Default, "C:\temp", opt)

    ' Upload files from C:\test to the root directory 
    FileSystem.TransferFiles(DiskFileSystem.Default, "C:\Test", CType(Nothing, IFileInfo()), system, "/", opt)

    ' Close the connection.
    client.Disconnect()
End Sub

And here is the usage code of the above method:

C#:

// ...

IRemoteFileSystem client;

if (useFtp)
{
    client = new Ftp();
    port = 21;
}
else
{
    client = new Sftp();
    port = 22;
}

// Manage files and directories either FTP or SFTP server using the same code.
SFTPandFTPConnection(client, "demo.componentpro.com", port, "test", "test");

VB.NET

' ...

Dim client As IRemoteFileSystem

If useFtp Then
    client = New Ftp()
    port = 21
Else
    client = New Sftp()
    port = 22
End If

' Manage files and directories either FTP or SFTP server using the same code.
SFTPandFTPConnection(client, "demo.componentpro.com", port, "test", "test")

Workaround for ‘Invalid Key Size’ error in the version 3.5

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

Setting AllowedMacAlgorithms

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

Setting AllowedHostKeyAlgorithms

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

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

How to verify SFTP Server’s Fingerprint

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

C#:

client.HostKeyVerifying += client_HostKeyVerifying;

VB.NET:

AddHandler client.HostKeyVerifying, AddressOf client_HostKeyVerifying

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

C#:

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

VB.NET

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

Using the SFTP component to connect to an SCP server

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

C#:

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

Getting absolute path of an object on an SFTP server

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

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

C#:

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

VB.NET:

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

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

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

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

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

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

Using Ultimate SFTP and FTP components to transfer a file

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

 

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

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

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

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

How to upload selected files and directories with UltimateSftp

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

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

C#

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

VB.NET

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