解决方法
我知道的最简单的代码是使用IoUtils单元的TDirectory:
function GetDirectoryCount(const DirName: string): Integer; begin Result := Length(TDirectory.GetDirectories(DirName)); end;
TDirectory.GetDirectories实际上返回一个包含目录名称的动态数组,所以这有点低效.如果你想要最有效的解决方案,那么你应该使用FindFirst枚举.
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;