Listing Event of the Ftp Class

Listing 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 FTP item or even parse the raw data of the received item line.

The following steps guide you on how to handle this event.

Handling Listing event

  1. Add using directives to your code to create aliases for existing namespaces and avoid having to type the fully qualified type names. The code looks similar to the following:
    C#  
    using ComponentSoft.Net; 
    VB.NET  
    Imports ComponentSoft.Net
  2. Create a new instance of the Ftp class.
  3. Register an event handler to the Listing event.
  4. Now you can connect to the FTP server with Connect methods. The code looks similar to the following:
    C#  
    // Create a new instance.
    Ftp client = new Ftp();
    // Register an event handler.
    client.Listing += client_Listing;
    // Connect to the FTP server.
    client.Connect("localhost");
    VB.NET  
    ' Create a new instance.
    Dim client As New Ftp()
    ' Register an event handler.
    AddHandler client.Listing, AddressOf client_Listing
    ' Connect to the FTP server.
    client.Connect("localhost")
  5. Use your user name and password to login with Authenticate methods. The code looks similar to the following:
    C#  
    // Authenticate.
    client.Authenticate("userName", "password");
    VB.NET  
    ' Authenticate.
    client.Authenticate("userName", "password")
  6. Do your tasks such as browsing a directory, upload, download files...
  7. After completing your work, call the Disconnect method to close the FTP session. 

Final example code

C#  
public void HandleListingEvent()
{
   
// Create a new instance.
   
Ftp client = new Ftp();
   client.Listing += client_Listing;
   
// Connect to the FTP server.
   
client.Connect("localhost");
   
// Or you can specify the FTP port with
   
// client.Connect("myserver", 21);
   
// Authenticate.
   
client.Authenticate("test", "test");  
   
// ...
   
// Get file list.
   
client.ListDirectory("");  
   
// ...
   
// Disconnect.
   
client.Disconnect();
}
void client_Listing(object sender, FtpListingEventArgs e)
{
   Console.WriteLine(
"Received raw line: " + e.RawData);
   Console.WriteLine(
"FTP file: " + e.File.ToString());
}
VB.NET  
Public Sub HandleListingEvent()
    ' Create a new instance.
    Dim client As New Ftp()
    AddHandler client.Listing, AddressOf client_Listing
    ' Connect to the FTP server.
    client.Connect("localhost")
    ' Or you can specify the FTP port with
    ' client.Connect("myserver", 21);
    ' Authenticate.
    client.Authenticate("test", "test")
    ' ...
    ' Get file list.
    client.ListDirectory("")
    ' ...
    ' Disconnect.
    client.Disconnect()
End Sub
Private Sub client_Listing(ByVal sender As Object, ByVal e As FtpListingEventArgs)
    Console.WriteLine("Received raw line: " & e.RawData)
    Console.WriteLine("FTP file: " & e.File.ToString())
End Sub

 

Security Overview and How to Connect to FTP/SSL Servers

This topic gives you an overview of Certificate and Security Modes for FTP/SSL. It also illustrates how to connect to FTP/SSL servers using ComponentSoft Ultimate FTP.

What is a digital certificate?

Authentication is important for secure communications. Users must be able to prove their identity to the entities they are communicating with. In addition, they must be able to verify the identity of the entity communicating with them. This is accomplished by presenting or verifying some form of trusted credentials.

A digital certificate is a common credential that provides authentication. A trusted organization, called a Certificate Authority (CA), assigns a certificate to a user or entity and the user or entity then uses the certificate to prove itself to the other side. You may configure your system to accept any number of Certificate Authorities but ComponentSoft does not recommend this configuration. Completing the following steps to access the Certificates dialog box:

  1. In the Control Panel, double-click Internet Options.
  2. Select the Content tab, and then click Certificates.

Where do I get a certificate?

Certificates must come from a trusted CA. A user submits a certificate request to a CA and the CA returns a certificate for the user to use. Certificate used on our ComponentSoft FTP server is generated by FileZila and CuteFTP. Listed below are some Certificate Authorities:

  • Microsoft Certificate Server - used for internal corporate Certificate delegation
  • VeriSign - (www.verisign.com) provides certificates for Internet users and servers

You always need a digital certificate installed to operate as a server. You only need a digital certificate installed on a client if the server requests authentication.

How does the authentication process work?

  1. The client normally initiates the TCP connection. The Connect method makes this TCP connection, sends a "client hello" message, and automatically responds to authentication requests received from the server.
  2. The server accepts the connection initiated by the client, constructs its digital credentials from the digital certificate referred to by the Server.Certificate Property, and sends its credentials to the client.
  3. Optionally, the server may also send an authentication request to the client.
  4. The client receives the server's credentials, verifies it against the CAs it is configured to trust, and responds with its own credentials if an authentication request is received.
  5. If the client and server cannot negotiate a mutually acceptable security protocol, an error is generated and the connection is closed.
  6. If the client cannot validate the server's credentials, an error is generated and the client closes the connection.
  7. If the server cannot validate the client's credentials (if requested), an error is generated and the server closes the connection.
  8. Once protocol negotiation and authentication is successful, secure encryption/decryption is performed on all data passing over the connection.
  9. The session is terminated when one side closes the connection.

What is a certificate store?

A certificate store is a location on the system (memory, disk, registry, etc.) where certificates are stored for use. There are three major system stores and other minor stores. The three major stores are:

  • MY - personal certificates go here. (e.g. ATP - ComponentSoft code signing)
  • ROOT - certificates for Trusted Root Certificate Authorities.
  • CA - all other certificates.

What are the system store and the machine store?

The system store is the certificate store located in the HKEY_CURRENT_USER registry key. The machine store is the certificate store located in the HKEY_LOCAL_MACHINE registry key. Applications installed as a service should store their certificates in the machine store since there is no current user when running as a service.

What is the X500 naming convention?

This is a format for creating a distinguished name. The different parts of the name are described below:

  • C - country you are in (ex. US).
  • S - state you are in (ex. California).
  • L - locality value or city (ex. Walnut).
  • O - your organization (ex. ATP, Inc.).
  • OU - organizational unit (ex. Software Development).
  • CN - common name; typically the name of the system or user (Ex. www.mydomain.com).

Here are some examples of X500 names:

  • C=US, S=New York, L=Syracuse, O=ATP, Inc., OU=ComponentSoft, CN=My Machine
  • C=US, S=Georgia, L=Atlanta, O=MyOrg, OU=Toy Department, CN=John Doe

Explicit connection

When the client connects to the server using SSL, an SSL negotiation is initialized, the connection is secured and all following communication is being protected. 

The code snippet below shows how to connect to an FTP server securely using Explicit security mode.

C#  
// Create a new instance.
Ftp client = new Ftp();
// Connect to the FTP server.
client.Connect("myserver", 21, SecurityMode.Explicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();

 

VB.NET

 
' Create a new instance.
Dim client As New Ftp()
' Connect to the FTP server.
client.Connect("myserver", 21, SecurityMode.Explicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()

 

Implicit Connection with FTP

Originally, a separate port was assigned to the SSL version of the FTP. The port number 990 is usually assigned for FTP/SSL. Upon connection to this port, an SSL negotiation starts immediately and the control connection is secured. All data connections are also secured implicitly in the same way. This is similar to the approach used by HTTPS.

The code snippet below shows how to connect to an FTP server securely using Implicit security mode in ComponentSoft FTP.

C#  
// Create a new instance.
Ftp client = new Ftp();
// Connect to the FTP server.
client.Connect("myserver", 990, SecurityMode.Implicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
client.DownloadFile("/my remote file.dat", "my local file");
// Disconnect.
client.Disconnect();

VB.NET  
' Create a new instance.
Dim client As New Ftp()
' Connect to the FTP server.
client.Connect("myserver", 990, SecurityMode.Implicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
client.DownloadFile("/my remote file.dat", "my local file")
' Disconnect.
client.Disconnect()

 

ComponentSoft FTP in Microsoft Windows PowerShell

ComponentSoft would like to illustrate how to use Ultimate FTP in PowerShell in this topic. PowerShell is the new command line and scripting language developed by Microsoft to helps IT professionals complete their tasks more efficiently with greater control and productivity on Microsoft Windows Platforms. The PowerShell contains more than 130 command line tools especially designed for administrators.

Windows PowerShell is built on top of the .NET Framework, so it gives administrators a wide-range of methods and extensions. With ComponentSoft FTP, now you can upload and download files to FTP server easily with a few lines of code. Since PowerShell accepts and returns .NET objects, FTP classes are accessible to the PowerShell, in which you can use the component to build a complex application like a C# or VB.NET application. This component can be downloaded from our componentsoft.net website.

To get start, we begin with uploading several files with a single line of code:

Unlike many other FTP components, Ultimate FTP enables you to upload and download multiple files with different extensions with a single line of code. We take advantages of this feature with the following PowerShell sample:

# Load DLL
 Add-Type -Path C:\InstalledDir\UltimateFtp.dll
 # Set source path and files to upload
 $sourcePath = "C:\Temp\*.ps1;*.dat;*.zip"
 # Set destination path
 $destinationPath = "/my dir"
 # Create a new instance of the Ftp class
 $ftp = New-Object ComponentSoft.Net.Ftp
 $ftp.Connect("myserver")
 $ftp.Authenticate("user", "pass")
 # Upload files
 $ftp.UploadFiles($sourcePath, $destinationPath)
 
 $ftp.Close()
 $ftp.Dispose()

Now we will download files from the FTP server to the local disk:

ComponentSoft gives you the ease-of-use of the FTP component not only in the upload methods, but also in the download methods. The following PowerShell code example demonstrates how to load the UltimateFtp.DLL assembly and download files from the FTP server:

# Load DLL
Add-Type -Path C:\InstalledDir\UltimateFtp.dll
# Set source path and files to upload
$sourcePath = "/my dir/*.ps1;*.dat;*.zip"
# Set destination path
$destinationPath = "C:\Temp2"
# Create a new instance of the Ftp class
$ftp = New-Object ComponentSoft.Net.Ftp
 $ftp.Connect("myserver")
 $ftp.Authenticate("user", "pass")
 # Download files
$ftp.DownloadFiles($sourcePath, $destinationPath)

$ftp.Close()
$ftp.Dispose()

Now you see with Ultimate FTP Component and a little knowledge of PowerShell language, you can build a comprehensive file transfer application running on the Windows PowerShell.

Downloading multiple files and directories

Download multiple files and directories with ComponentSoft UltimateFtp is really simple. You only need to call the DownloadFiles method with few parameters. The component will do the rest of hard work for you. It will loop through the specified directory, find files that match the specified search criteria, create threads, and start downloading. The steps belows show you how to use ComponentSoft FTP to download files with three threads.

Downloading files using multiple threads

Add using directives to your code to create aliases for existing namespaces and avoid having to type the fully qualified type names. The code looks similar to the following:

C# Copy Code
using ComponentSoft.Net;
using ComponentSoft.IO;
VB.NET Copy Code
Imports ComponentSoft.Net
Imports ComponentSoft.IO

Create a new instance of the Ftp class.
C# Copy Code
// Create a new instance.
Ftp client = new Ftp();
VB.NET Copy Code
' Create a new instance.
Dim client As New Ftp()
Register event handlers to the ThreadCompleted and ThreadsCompleted events to get informed when a thread has completed and all threads have completed. The code looks similar to the following:
C# Copy Code
client.ThreadCompleted += client_ThreadCompleted;
client.ThreadsCompleted += client_ThreadsCompleted;
VB.NET Copy Code
AddHandler client.ThreadCompleted, AddressOf client_ThreadCompleted
AddHandler client.ThreadsCompleted, AddressOf client_ThreadsCompleted

Now pass all needed parameters to the DownloadFiles method. The code looks similar to the following:
C# Copy Code
// Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
client.DownloadFiles("/my folder", "c:\\my folder", 3, true);
VB.NET Copy Code
' Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
client.DownloadFiles("/my folder""c:\my folder", 3, True)

Final example code

C# Copy Code
public void DoMultiThreadsDownloadFiles()
{
   
// Create a new instance of the ComponentSoft.Net.Ftp class.
   
Ftp client = new Ftp();
   
// Connect to the server.
   
client.Connect("server");
   
// Authenticate.
   
client.Authenticate("user", "pass");
   client.CommandResponse += client_ResponseRead;
   client.ThreadCompleted += client_ThreadCompleted;
   client.ThreadsCompleted += client_ThreadsCompleted;
   
// ...
   
// Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
   
client.DownloadFiles("/my folder", "c:\\my folder", 3, true);
   
// ...
   
client.Disconnect();
}
void client_ThreadsCompleted(object sender, ThreadsCompletedEventArgs e)
{
   Console.WriteLine(
"Multi-threads file transfer completed");
}
void client_ThreadCompleted(object sender, ThreadCompletedEventArgs e)
{
   Console.WriteLine(
string.Format("Thread ID {0} completed", e.FileSystem.ThreadId));
}
void client_ResponseRead(object sender, CommandResponseEventArgs e)
{
   Ftp client = (Ftp)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);
}
VB.NET Copy Code
Public Sub DoMultiThreadsDownloadFiles()
    ' Create a new instance.
    Dim client As New Ftp()
    ' Connect to the server.
    client.Connect("server")
    ' Authenticate.
    client.Authenticate("user""pass")
    AddHandler client.CommandResponse, AddressOf client_ResponseRead
    AddHandler client.ThreadCompleted, AddressOf client_ThreadCompleted
    AddHandler client.ThreadsCompleted, AddressOf client_ThreadsCompleted
    ' ...
    ' Download files and subdirectories from "/my folder" to "c:\\my folder" using 3 threads. This waits untils these threads complete.
    client.DownloadFiles("/my folder""c:\my folder", 3, True)
    ' ...
    client.Disconnect()
End Sub
Private Sub client_ThreadsCompleted(ByVal sender As ObjectByVal e AsThreadsCompletedEventArgs)
    Console.WriteLine("Multi-threads file transfer completed")
End Sub
Private Sub client_ThreadCompleted(ByVal sender As ObjectByVal e AsThreadCompletedEventArgs)
    Console.WriteLine(String.Format("Thread ID {0} completed", e.FileSystem.ThreadId))
End Sub
Private Sub client_ResponseRead(ByVal sender As ObjectByVal e AsCommandResponseEventArgs)
    Dim client As Ftp = CType(sender, Ftp)
    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

You may want to see other topics:

Uploading selected files and directories

 

How to upload selected files and directories

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

The following steps show you how to use the UploadFiles method to upload multiple files to the remote server. To download multiple files, see this http://www.ftpcomponent.net/downloading-multiple-files-and-directories

C#



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


VB.NET

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

Introduction to ComponentSoft.net FTP Component for .NET

ComponentSoft.net Ultimate FTP/FTPS (FTP over TLS/SSL) .NET Component offers a comprehensive interface for FTP, enabling you to quickly and easily incorporate Standard File Transfers and Secure File Transfers over TLS/SSL in your applications, as well as remote file management using FTP. In addition to downloading and uploading by file nameURL, and wild card masks, the FTP library also supports remote file management functionality such as directory listings and the ability to renamedelete and move files on the server. The component also offers the flexibility, ease of use and rapid development features of a component without the complexities of working with the native socket class or in-depth knowledge of how the File Transfer Protocols are implemented. In most cases, only a few lines of code are required to implement a file transfer in your application. The set of properties and methods is sufficiently rich to enable you to take advantage of features such as the resumption of interrupted transfers, passive mode operation in the presence of firewalls, automatic file verification and support for custom server commands.

In addition to supporting standard file transfers, ComponentSoft Ultimate FTP Component also supports multi-thread file transfers as well as data compression on-the-fly with built-in Zlib classes to speed up the transfers.

To reduce your effort writing a number of classes for different file systems such as FTP, SFTP, ZIP, Local Disk, and Virtual Disk, we introduce the Unified File System that makes the management of files on these systems seamless. Moreover, it allows you to use the same code to transfer files and directories directly from one to other file systems. As a benefit, you should only need to write one class that works with these file systems nicely. There is no need to learn more about other File Transfer Protocols, all the complicated work is done by the Ultimate File System. For more information, please visit this topic.

To help you to become familiar with the features of the component, a number of well documented samples and topics were added to the comprehensive integrated online documentation which can be found at this web page.

If you need SSH Secure FTP (SFTP) Component, please visit SSH Secure FTP (SFTP) Library page.

ComponentSoft FTP Key Features

  • Uploaddownloadappendrename and delete file.
  • Uploaddownload, or Remove entire directory (including subdirectories and files) quickly with a single line of code
  • Upload and download multiple files using wildcards mask with a single line of code
  • Support for files over 4GB
  • Parse listings automatically
  • Supports both ASCII and binary transfers
  • Supports restarting interrupted file transfers
  • Abort operations smoothly
  • Synchronizes folders easily
  • Supports Multi-threading. You can use as many threads as you want to speed up file transfers
  • Unified Remote File System allows you to directly and easily transfer and synchronize files between an FTP file system and other file systems such as FTP, SCP, ZIP, Disk, Memory, etc.
  • File transfer monitoring support with progress event
  • Fully supports both event-driven (asynchronous) and blocking (synchronous) application designs
  • Send and receive files to or from disk or memory streams. This allows you to compress and decompress ZIP files on-the-fly
  • Built-in Zlib streams
  • Filter files on name with wildcards mask or regular expression, size, or last modified date
  • Resume previously interrupted file
  • Allows you to check the exact transferring state like uploading, downloading, etc.
  • Compliant with RFC 959, RFC 1579 and many common extensions
  • Progress event argument contains full information about the file transfer such as: File size, transfer percentage, transfer speed, time left, etc.
  • Compression support (MODE Z)
  • Reusable block mode transfer support (MODE B)
  • Raw FTP command and response support
  • Supports ASP.NET Medium Trust environment configuration
  • more...

 

Security and Reliability

The Ultimate FTP Component for .NET Framework also supports secure SSL and TLS connections. By simply setting a few properties, a secure connection using 128-bit encryption can be established, providing your application with the greatest flexibility and highest level of security available. Even advanced options such as client certificates are seamlessly supported. The security features are completely integrated into the component itself, meaning that there's no external dependencies on third-party components or libraries.

Supports HTTP Connect, SOCKS4, SOCKS4A & SOCKS5 Proxy Servers

ComponentSoft Ultimate FTP provides full support for Proxy Servers such as HTTP CONNECT, SOCKS4, SOCKS4A, and SOCKS5. By simply setting a few properties, you are able to download and upload files and directories from/to FTP servers through the desired proxy server.

Support for IPv6, the next generation Internet protocol

IPv6 (Internet Protocol version 6), the next-generation protocol designed by the IETF (Internet Engineering Task Force), will gradually replace the current version of the Internet Protocol, IPv4.

With Ultimate FTP Component, users have an integrated service assurance solution that will provide them with FTP, and Proxy capabilities in mixed IPv4 and IPv6 environments. This helps organizations with the adoption of and the transition to IPv6 by making the management of such networks seamless.

.NET Technology

By using 100% managed code written in C#, the Ultimate FTP component takes advantage of the numerous built-in features of the .NET Framework to enhance performance, moreover, the component is CLS compliant, and it does not use any unsafe blocks for minimal permission requirements.

Supports many .NET Platforms

Ultimate FTP Component for .NET supports the following platforms:

  • Windows Forms
  • Web Forms
  • Web Services

 

In addition, it is also possible to use the component in PowerShell - Microsoft’s new command console and scripting language.

Ultimate FTP is fully compatible with Visual Studio 2005 and Visual Studio 2008, as well as upcomming release of Visual Studio 2010. As a benefit, you are always up-to-date with Microsoft's Technologies when using our products.

Supports event-driven (Asynchronous) and blocking (Synchronous) Design

Most applications written with the FTP component will be synchronous. Synchronous method gives you the ease-of-use, but it can only returns the control back to the caller after it has finished, meaning that it blocks the execution of the caller for a period of time. Using synchronous method is recommended when you only need to execute one FTP operation at a time.

You might decide that your design requires an asynchronous operation when it is needed to manage email messages simultaneously. Asynchronous methods provide a great deal of power. Asynchronous method is executed on a thread separate from the calling thread. Such operation is useful when an FTP operation is time consuming and other codes need to execute without waiting for the initial operation to complete. In addition, the user interface will be most responsive when asynchronous methods are used.

Flexibility

The FTP component can be used with a wide variety of programming languages and different types of development environments. As it was written in 100% managed Visual C#, it is fully supported by languages such as Visual BasicVisual C#J#Managed C++Borland C# Builder, and Delphi.

Fully Documented

We know that no product can be complete without comprehensive documentation. This is why the ComponentSoft FTP for .NET product includes a Developer's Guide and a complete Technical Reference which documents every property, method and event supported by the component. A context-sensitive online help is included with the product which can be accessed directly from within the development environment.

Lots of complete FTP client samples in VB.NET, C#, and ASP.NET

In addition to the fully documented Developer's Guide and a complete Technical Reference, Ultimate FTP component also includes a number of samples with full source code which help you to become familiar with the features of the component and provide code which you can re-use in your own applications. The setup package contains three complete FTP client applications: FTP Console ClientFTP WinForms Client, and FTP AJAX WebForms Client.

Royalty-free and Unlimited Server Deployment

All ComponentSoft products include royalty-free distributation, for unlimited site deployment. It meansapplications built using the Ultimate FTP component can be redistributed to as many end-users as needed without additional royalties or runtime licensing fees.

 

ComponentSoft

20496 Pso Del Prado

91789 Walnut

USA

Website: http://www.componentsoft.net

E-Mail: info@componentsoft.net

Phone: +1 (917) 338 4679