【问题标题】:Counting folders within a folder计算文件夹中的文件夹
【发布时间】:2011-09-05 09:48:22
【问题描述】:

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

【问题讨论】:

    标签: delphi delphi-2010


    【解决方案1】:

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

    【讨论】:

    • 大卫,你为什么在 FindFirst 中使用 faAnyFile 而不是 faDirectory
    • @Whiler 我想包括只读对象、隐藏对象、系统对象。
    • @David,如果 GetDirectoryCount 为零,是否可能存在泄漏?文档说只有在匹配的 FindFirst 正常时才调用 FindClose。
    • @LU RD 是的,我认为你是对的。我很懒惰。现在好点了吗?
    • 如果文件夹存在,至少有2个结果:. & .. ;o) 还是在某些特定情况下可以不使用它们?
    猜你喜欢
    • 1970-01-01
    • 2016-02-25
    • 2017-12-25
    • 2020-02-03
    • 2015-06-27
    • 1970-01-01
    • 2017-11-14
    • 2019-01-06
    • 2012-11-06
    相关资源
    最近更新 更多