Does anyone know a code I can use to count the number of folders in a specified directory?
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.
To count all the files and directories in the current directory and subdirectories, type dir *. * /s at the prompt.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With