各位朋友:
    如果路径为:“C:\windows”,如何写函数,才能检测出Windows这个目录下面有多少个目录,并且获得该目录下所有目录的文件名?例如:Windows目录下面有三个目录:Win1、Win2、Win3,而Win1里面又有几十个子目录,Win2和Win3里面也有几十个子目录,我只想统计出Windows目录下层有Win1 Win2 Win3这三个目录,并且可以知道这三个目录的目录名就可以了。    请问有没相关的函数可以实现,请各位朋友赐教,多谢!!!

解决方案 »

  1.   

    有简单方法和复杂方法.
    简单方法:
    放一个TShellListView
    设置其Root属性为C:\windows
    通过以下熟悉可以访问其子路径:
      ShellListView1.Items.Count;
      ShellListView1.Items[I].Caption复杂方法:
    用FindFirst,FindNext,FindClose等函数示例如下:
    procedure TForm1.Button1Click(Sender: TObject);
    var
      sr: TSearchRec;
      FileAttrs: Integer;
    begin
      FileAttrs := 0;
      FileAttrs := FileAttrs + faHidden;
      FileAttrs := FileAttrs + faDirectory;
      Memo1.Clear;  with Memo1.Lines do
      begin
        if FindFirst('C:\Windows\*', FileAttrs, sr) = 0 then
        begin
          repeat
            if (sr.Attr and FileAttrs) = sr.Attr then
            begin
              if (sr.Name<>'.')and(sr.Name<>'..') then
                Add(sr.Name);
            end;
          until FindNext(sr) <> 0;
          FindClose(sr);
          showmessage('目录数='+IntToStr(Count));
        end;
      end;
    end;
      

  2.   

    procedure EnumPath(Path:String);
    var
      Sr: TSearchRec;
    begin       
      if Path[Length(Path)]<>'\' then
        Path:=Path+'\';
      If FindFirst(Path+'*.*', faAnyFile, Sr)=0 Then
      Begin
        if (Sr.Attr=faDirectory) and (Sr.Name<>'.') then begin
          EnumPath(Path+Sr.Name)//归递调用
        end
        else if (sr.Name<>'.') and (sr.Name<>'..') then
            ShowIT(Path+Sr.Name);
        While FindNext(sr)=0 do
        Begin
          if (sr.Attr=faDirectory) and (sr.Name<>'.') and (sr.Name<>'..') then begin
            EnumPath(Path+Sr.Name)//归递调用
          end
          else if (sr.Name<>'.') and (sr.Name<>'..') then
            ShowIT(Path+Sr.Name);
        End;
      End;   
      FindClose(Sr);
    end;以上是一个归递调用列出目录和其下所有子目录的算法适当修改就可以满足你的要求,以下是我简单修改的,没有调试 :( 应该没问题procedure EnumPath(Path:String);
    var
      Sr: TSearchRec;
    begin       
      if Path[Length(Path)]<>'\' then
        Path:=Path+'\';
      If FindFirst(Path+'*.*', faAnyFile, Sr)=0 Then
      Begin
        if (sr.Attr=faDirectory) and (sr.Name<>'.') and (sr.Name<>'..') then begin
          ShowMessage(Path+Sr.Name)
        end
        While FindNext(sr)=0 do
        Begin
          if (sr.Attr=faDirectory) and (sr.Name<>'.') and (sr.Name<>'..') then begin
            ShowMessage(Path+Sr.Name)
          end
        End;
      End;   
      FindClose(Sr);
    end;
    ------------------
    你在程序中调用
    EnumPath("C:\Windows\")