Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting folders within a folder

Does anyone know a code I can use to count the number of folders in a specified directory?

like image 763
ple103 Avatar asked Sep 05 '11 09:09

ple103


People also ask

How do I count the number of folders in a folder?

Alternatively, select the folder and press the Alt + Enter keys on your keyboard. When the Properties window opens, Windows 10 automatically starts counting the files and folders inside the selected directory. You can see the number of files and folders displayed in the Contains field.

How do I count files in a folder and subfolders?

To count all the files and directories in the current directory and subdirectories, type dir *. * /s at the prompt.

How do I count the number of files in multiple folders?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window.


1 Answers

The very simplest code that I know of uses TDirectory from the IOUtils unit:

function GetDirectoryCount(const DirName: string): Integer;
begin
  Result := Length(TDirectory.GetDirectories(DirName));
end;

TDirectory.GetDirectories actually returns a dynamic array containing the names of the directories so this is somewhat inefficient. If you want the most efficient solution then you should use FindFirst to enumerate.

function GetDirectoryCount(const DirName: string): Integer;
var
  res: Integer;
  SearchRec: TSearchRec;
  Name: string;
begin
  Result := 0;
  res := FindFirst(TPath.Combine(DirName, '*'), faAnyFile, SearchRec);
  if res=0 then begin
    try
      while res=0 do begin
        if SearchRec.FindData.dwFileAttributes and faDirectory<>0 then begin
          Name := SearchRec.FindData.cFileName;
          if (Name<>'.') and (Name<>'..') then begin
            inc(Result);
          end;
        end;
        res := FindNext(SearchRec);
      end;
    finally
      FindClose(SearchRec);
    end;
  end;
end;
like image 180
David Heffernan Avatar answered Oct 22 '22 10:10

David Heffernan