Get file or directory information using Ultimate FTP

The FTP protocol has the standard command “LIST” to list files and directories. A LIST request asks the server to send the contents of a directory over the data connection already established by the client. The LIST format varies widely from server to server. The most common format is /bin/ls (UNIX) format, which is difficult to parse with even moderate reliability. This poses a severe problem for clients that need more information than names.

In this article, we are going to show some examples that get files or directory information from the remote FTP server using the Ultimate .NET FTP Library. Ultimate FTP library can handle any format. It includes Windows, UNIX, and Linux systems. It offers provision to determine whether an FTP Server supports standardized MLSD command then it uses MLSD instead of LIST. The Ftp class automatically does all the hard work such as detecting FTP Server OS, determining the listing type, listing directories, and calculating the total content size.

Directory Info

List Directory Content

To list the files and directories in any directory to which you have access use ListDirectory() method of Ftp class. You’ll receive FtpFileInfo collection. Using this collection, you can retrieve information about directory content (file, subdirectory, symlink, etc.). Ultimate FTP offers you various options to retrieve directory content.

  • You have to pass the path to the directory. If you do not pass a parameter to this method, it will list the content of the current directory.
  • You can specify search condition if you want only specific files to be retrieved while listing directory content.
  • You can opt to get a list of files and directories in raw Unix-like text format (similar to ls –l command).
  • You can sort directory entries received from ListDirectory & Search methods because by default they return the results in the same order as returned by the server.
  • You can use LINQ queries on the FileInfoCollection object returned by ListDirectory & Search methods.
  • Almost all directory listing formats are supported by Ultimate FTP. However, it might be possible that some FTP server has rare directory listing formats. In such cases, you can implement your parser to handle the issue.
  • Following code snippet shows how to implement the above points listed in bullet points from a) to e)

    C#:

    // Create a new class instance.
    using (Ftp client = new Ftp())
    {
    
    // Connect to the FTP server.
    client.Connect("myserver");
    
    // Authenticate.
    client.Authenticate("test", "test");
    
    // ... 
    
    // Get information of all files and directories in '/' remote dir. 
    foreach (FtpFileInfo info in client.ListDirectory("/"))
    {
        Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions);
    }
    
    #region a)
    // Many FTP servers do not support ListDirectory with parameter method, Hence, we have to 
    // change the current directory before calling ListDirectory. 
    // Get names of all files and directories in '/my folder' remote dir.
    client.SetCurrentDirectory("/my folder");
    foreach (FtpFileInfo info in client.ListDirectory())
    {
        Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions);
    }
    #endregion a)
    
    #region b)
    // List files with search condition. 
    // List all files that have .exe extension in "/" folder. 
    foreach (FtpFileInfo info in client.ListDirectory("/", new NameSearchCondition("*.exe")))
    {
        Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions);
    }
    #endregion b)
    
    
    #region c)
    // Get raw information of all files and directories in '/' remote dir. 
    foreach (string raw in client.ListRawName("/"))
    {
        Console.WriteLine(raw);
    }
    #endregion c)
    
    #region d)
    // Get file list of the current directory.
    FileInfoCollection list = client.ListDirectory();
    
    // Sort the list.
    list.Sort(new FileInfoComparer(FileInfoComparisonMethod.LastWriteTime, false));
    #endregion d)
    
    #region e)
    // List all files in "/myfolder" remote dir. 
    FileInfoCollection mylist = client.ListDirectory("/myfolder");
    var filteredList = list.Cast<FtpFileInfo>()
        .Where(item => item.IsFile && item.Length > 4096)
        .OrderBy(item => item.Name);
    
    var filteredList2 = from FtpFileInfo item in list
                        where item.IsFile && item.Length > 4096
                        orderby item.Name
                        select item;
    #endregion e)
    
    // Disconnect.
    client.Disconnect();
    

    VB.NET

    ' Create a new class instance. 
    Using client As New Ftp()
    
        ' Connect to the FTP server.
        client.Connect("myserver")
    
        ' Authenticate.
        client.Authenticate("test", "test")
    
        ' ... 
    
        ' Get information about all files and directories in '/' remote dir. 
        For Each info As FtpFileInfo In client.ListDirectory("/")
            Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions)
        Next info
    #Region "a)"
    
        ' Many FTP servers do not support ListDirectory with parameter method. Hence, we have to 
        ' change the current directory before calling ListDirectory. 
        ' Get names of all files and directories in '/my folder' remote dir.
        client.SetCurrentDirectory("/my folder")
        For Each info As FtpFileInfo In client.ListDirectory()
            Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions)
        Next info
    #End Region
    #Region "b)"
        ' List files with search condition. 
        ' List all files that have .exe extension in "/" folder. 
        For Each info As FtpFileInfo In client.ListDirectory("/", New NameSearchCondition("*.exe"))
            Console.WriteLine("Name: {0}, Permissions: {1}", info.Name, info.Permissions)
        Next info
    #End Region
    
    #Region "c)"
        ' Get raw information of all files and directories in '/' remote dir. 
        For Each raw As String In client.ListRawName("/")
            Console.WriteLine(raw)
        Next raw
    #End Region
    
    #Region "d)"
        ' Get file list of the current directory. 
        Dim list As FileInfoCollection = client.ListDirectory()
    
        ' Sort the list.
        list.Sort(New FileInfoComparer(FileInfoComparisonMethod.LastWriteTime, False))
    #End Region
    
    
    #Region "e)"
        ' List all files in "/myfolder" remote dir. 
        Dim list As FileInfoCollection = client.ListDirectory("/myfolder")
        Dim filteredList = list.Cast(Of FtpFileInfo)().Where(Function(item) item.IsFile AndAlso item.Length > 4096).OrderBy(Function(item) item.Name)
    
        Dim filteredList2 = From item As FtpFileInfo In list
                            Where item.IsFile AndAlso item.Length > 4096
                            Order By item.Name
                            Select item
    #End Region
        ' Disconnect.
        client.Disconnect()
    End Using
    

    Custom Directory listing parser sample

    C#:

    static void Main()
    {
        // Custom parer 
        // Create a new instance of the Ftp class. 
        using (Ftp client = new Ftp())
        {
            // Connect to the server. 
            client.Connect(serverName);
    
            // Authenticate the user. 
            client.Authenticate(userName, password);
    
            // Register event handler. 
            FtpFileInfo.ItemParse += FtpFileInfoOnItemParse;
    
            // Get listings of the current directory. 
            client.ListDirectory();
        }
    }
    
    private static void FtpFileInfoOnItemParse(object sender, FtpFileInfoParseEventArgs e)
    {
        // If the listing has been parsed correctly, return that item. 
        if (e.Item != null && !string.IsNullOrEmpty(e.Item.Name))
            return;
    
        // This parses the item name from the raw line. 
        string name = e.RawLine.Substring(39);
    
        // Check if the listing is a directory. 
        bool isDirectory = e.RawLine.IndexOf("-DIR-") != -1;
    
        // Create a new FtpFileInfo item and fill it with the parsed information 
        e.Item = new FtpFileInfo(
                        (Ftp)sender,
                        name,
                        name,
                        0,
                        isDirectory ? FtpFileType.Directory : FtpFileType.File, 
                        DateTime.MinValue, 
                        DateTime.MinValue);
    }
    

    VB.NET

    Shared Sub Main()
        ' Custom parer 
        ' Create a new instance of the Ftp class. 
        Using client As New Ftp()
            ' Connect to the server. 
            client.Connect(serverName)
    
            ' Authenticate the user. 
            client.Authenticate(userName, password)
    
            ' Register event handler. 
            AddHandler FtpFileInfo.ItemParse, AddressOf FtpFileInfoOnItemParse
    
            ' Get listings of the current directory. 
            client.ListDirectory()
        End Using
    End Sub 
     
    Private Shared Sub FtpFileInfoOnItemParse(ByVal sender As Object, ByVal e As FtpFileInfoParseEventArgs)
        ' If the listing has been parsed correctly, return that item. 
        If e.Item IsNot Nothing AndAlso (Not String.IsNullOrEmpty(e.Item.Name)) Then 
            Return 
        End If 
     
        ' This simply parses the item name from the raw line. 
        Dim name As String = e.RawLine.Substring(39)
    
        ' Check if the listing is a directory. 
        Dim isDirectory As Boolean = e.RawLine.IndexOf("-DIR-") <> -1
    
        ' Create a new FtpFileInfo item and fill it with the parsed information 
        If isDirectory Then 
            e.Item = New FtpFileInfo(CType(sender, Ftp), name, name, 0,FtpFileType.Directory, Date.MinValue, Date.MinValue)
        Else 
            e.Item = New FtpFileInfo(CType(sender, Ftp), name, name, 0,FtpFileType.File, Date.MinValue, Date.MinValue)
        End If 
    End Sub
    

    Retrieving necessary File information using FTP

    Using Ultimate FTP, you can retrieve basic file information like file size, last modification date, etc.

    Get directory size

    The following code snippet shows how to get directory size.

    C#:

    using System;
    using ComponentPro.Net;
    using ComponentPro.IO;
    
    ...
    
    void CalculateDirSize()
    {
        // Create a new class instance. 
        Ftp client = new Ftp();
    
        // Connect to the FTP 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);
    }
    

    VB.NET

    Imports ComponentPro.Net
    Imports ComponentPro.IO
    
    ...
    
    Private Sub CalculateDirSize()
        ' Create a new class instance. 
        Dim client As New Ftp()
    
        ' Connect to the FTP server. 
        client.Connect("myserver")
    
        ' Authenticate. 
        client.Authenticate("userName", "password")
    
        ' ... 
     
        ' Calculate the 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
    

45-Day Money Back Guarantee

We will refund your full money in 45 days
if you are not satisfied with our products

Buy Now

Dont miss out Get update on new articles and other opportunities