计算文件夹内的文件夹数量

发布于 2024-12-02 17:39:09 字数 32 浏览 0 评论 0原文

有谁知道我可以用来计算指定目录中文件夹数量的代码?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

a√萤火虫的光℡ 2024-12-09 17:39:09

我所知道的最简单的代码使用来自 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;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文