Get an FTP folder size using FluentFTP

439 Views Asked by At

I want to list out all the folder names and sizes in / path In my case I have two folders in `/ path

  1. XYZ (12MB)
  2. ABC (10MB)

I want to get names and sizes using FluentFTP to achieve it with blazor.
I am using BabyFTP as a test FTP server.

what I have done is

private void GetFileSize()
{
    using (var conn = new FtpClient("127.0.0.1"))
    {
        conn.Connect();

        foreach (FtpListItem item in conn.GetListing("/"))
        {
            Console.WriteLine(item.Name);
            Console.WriteLine(item.Size);
        }
        conn.Disconnect();
    }
}

But I am getting Name correct but I am getting Size as 0. How to get size of each folder?

1

There are 1 best solutions below

0
Martin Prikryl On

(Sub)directory entries in directory listing do not have sizes. Anywhere, just check Windows dir command or unix ls command.

You have to recursively sum sizes of all contained files. Like this:

ulong GetDirectorySize(FtpClient client, string path)
{
    ulong result = 0;
    foreach (var entry in client.GetListing(path))
    {
        if (entry.Type == FtpObjectType.File)
        {
            result += (ulong)entry.Size;
        }
        else if (entry.Type == FtpObjectType.Directory)
        {
            result += GetDirectorySize(client, entry.FullName);
        }
    }
    return result;
}