Listing a directory Asynchronously

In UltimateFtp, you can use BeginListDirectory, BeginListName or BeginListRawName methods of the Ftp class to asynchronously retrieve the list of files and directories in the specified directory on the FTP server. These methods retrieve the list asynchronously with execution occurring on a new thread, therefore it allows your next line of code to execute  immediately. The event ListDirectoryCompleted, ListNameCompleted or ListRawNameCompleted of the Ftp class under namespace Atp.Net is raised when the BeginListDirectory, BeginListName or BeginListRawName is complete. In the handler method of the ListDirectoryCompleted, ListNameCompleted or ListRawNameCompleted event, you need to call the EndListDirectory, EndListName or EndListRawName method to finish the asynchronous operation.

The following image shows how the FTP Client Demo sample project shows contents of an FTP directory:

FTP Client Demo

To retrieve the list of files and directories in a directory on the FTP server asynchronously, you can simply perform the following steps

  1. Add the FTP component to your application. See Creating a WinForms Application or Creating a Web Application for more details.
  2. Add using directives to your code to create aliases for existing namespaces and avoid having to type the fully qualified type names.

  3. Create a new instance of the Ftp class.
  4. Now you can connect to the FTP server with Connect or BeginConnect methods. The code looks similar to the following:
    C#  
    // Create a new instance.
    Ftp client = new Ftp();
    // Connect to the FTP server.
    client.Connect("myserver");
    // Or you can specify the FTP port with
    // client.Connect("myserver", 21);
    VB.NET  
    ' Create a new instance.
    Dim client As New Ftp()
    ' Connect to the FTP server.
    client.Connect("myserver")
    ' Or you can specify the FTP port with
    ' client.Connect("myserver", 21);

  5. Now you can call the BeginListDirectory to asynchronously retrieve the list of files and directories in the specified directory on the FTP server. Prior to calling BeginListDirectory method, you have to register an event handler to the ListDirectoryCompleted event (you do not need to do that before each call to the BeginListDirectory method, just before the first call). Upon completion of the operation, Ultimate FTP will raise the ListDirectoryCompleted event. When the event is raised, access information contained in the AsyncMethodCompletedEventArgs object. The code looks similar to the following:
    C#  
    // Register an event handler.
    client.ListDirectoryCompleted += client_ListDirectoryCompleted;
    // Get information of all files and directories in '/' remote dir.
    client.BeginListDirectory("/");
    VB.NET  
    ' Register an event handler.
    AddHandler client.ListDirectoryCompleted, AddressOf client_ListDirectoryCompleted
    ' Get information of all files and directories in '/' remote dir.
    client.BeginListDirectory("/")
  6. Now you need to write the code for client_ListDirectoryCompleted event handler. And in the client_ListDirectoryCompleted event handler, write your own code to do something like displaying the received list... The code looks similar to the following:
    C#  
    void client_ListDirectoryCompleted(object sender, AsyncMethodCompletedEventArgs e)
    {
       Ftp client = (Ftp)sender;
       
    try
       {
           
    // Get information of all files and directories in '/' remote dir.
           
    foreach (FtpFileInfo info in client.EndListDirectory(e.AsyncResult))
           {
               Console.WriteLine(
    "Name: {0}, UserId: {1}, Permissions: {2}", info.Name, info.UserId, info.Permissions);
           }
       }
       
    catch (Exception exc)
       {
           Console.WriteLine(
    "Error: " + exc.ToString());
       }
    }
    VB.NET  
    Private Sub client_ListDirectoryCompleted(ByVal sender As Object, ByVal e As AsyncMethodCompletedEventArgs)
        Dim client As Ftp = CType(sender, Ftp)
        Try
            ' Get information of all files and directories in '/' remote dir.
            For Each info As FtpFileInfo In client.EndListDirectory(e.AsyncResult)
                Console.WriteLine("Name: {0}, UserId: {1}, Permissions: {2}", info.Name, info.UserId, info.Permissions)
            Next info
        Catch exc As Exception
            Console.WriteLine("Error: " & exc.ToString())
        End Try
    End Sub
  7. After completing your work, call the Disconnect method to close the FTP session. 

Final Example Code using Ultimate FTP

C#  
public void DoAsyncListDirectory()
{
   
// Create a new instance.
   
Ftp client = new Ftp();
   
// Connect to the FTP server. (i.e. yourdomain.com)
   
client.Connect("myserver");
   
// Authenticate.
   
client.Authenticate("test", "test");
   
// ...
   
// Register an event handler.
   
client.ListDirectoryCompleted += client_ListDirectoryCompleted;
   
// Get information of all files and directories in '/' remote dir.
   
client.BeginListDirectory("/");
   
// ...
   
// Disconnect.
   
client.Disconnect();
}
void client_ListDirectoryCompleted(object sender, AsyncMethodCompletedEventArgs e)
{
   Ftp client = (Ftp)sender;
   
try
   {
       
// Get information of all files and directories in '/' remote dir.
       
foreach (FtpFileInfo info in client.EndListDirectory(e.AsyncResult))
       {
           Console.WriteLine(
"Name: {0}, UserId: {1}, Permissions: {2}", info.Name, info.UserId, info.Permissions);
       }
   }
   
catch (Exception exc)
   {
       Console.WriteLine(
"Error: " + exc.ToString());
   }
}

VB.NET  
Public Sub DoAsyncListDirectory()
    ' Create a new instance.
    Dim client As New Ftp()
    ' Connect to the FTP server.
    client.Connect("atp-inc.net")
    ' Authenticate.
    client.Authenticate("test", "test")
    ' ...
    ' Register an event handler.
    AddHandler client.ListDirectoryCompleted, AddressOf client_ListDirectoryCompleted
    ' Get information of all files and directories in '/' remote dir.
    client.BeginListDirectory("/")
    ' ...
    ' Disconnect.
    client.Disconnect()
End Sub
Private Sub client_ListDirectoryCompleted(ByVal sender As Object, ByVal e As AsyncMethodCompletedEventArgs)
    Dim client As Ftp = CType(sender, Ftp)
    Try
        ' Get information of all files and directories in '/' remote dir.
        For Each info As FtpFileInfo In client.EndListDirectory(e.AsyncResult)
            Console.WriteLine("Name: {0}, UserId: {1}, Permissions: {2}", info.Name, info.UserId, info.Permissions)
        Next info
    Catch exc As Exception
        Console.WriteLine("Error: " & exc.ToString())
    End Try
End Sub

After listing a directory successfully, you can either use the asynchronous methods or synchronous methods to transfer files. For more details on transferring files, see this Transferring multiple files using Ultimate FTP topic.

Click here to download the Ultimate FTP Component for .NET, or here to download the .NET CF version.

 

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 Atp.Net; 
    VB.NET  
    Imports Atp.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

 

Click here to download the Ultimate FTP Component for .NET, or here to download the .NET CF version.