开发者

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜