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.

 

Downloading multiple files and directories

Download multiple files and directories with ATP 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 Ultimate 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 Atp.Net;
using Atp.IO;
VB.NET Copy Code
Imports Atp.Net
Imports Atp.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 Atp.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

 

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