Counting folders within a folder
Does anyone know a code I can use to count th开发者_JAVA百科e number of folders in a specified directory?
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;
精彩评论