1. Home
  2. Computing & Technology
  3. Delphi Programming

Get Subdirectories of a specified Directory

By Zarko Gajic, About.com

When developing applications that need to operate on files and directories it is a common task to, for example, get the list of all sub-directories for a given directory.

GetSubDirectories

The GetSubDirectories fills a TStrings with all the subdirectories for a given directory:
//fils the "list" TStrings with the subdirectories of the "directory" directory
procedure GetSubDirectories(const directory : string; list : TStrings) ;
var
  sr : TSearchRec;
begin
  try
    if FindFirst(IncludeTrailingPathDelimiter(directory) + '*.*', faDirectory, sr) < 0 then
      Exit
    else
    repeat

      if ((sr.Attr and faDirectory <> 0) AND (sr.Name <> '.') AND (sr.Name <> '..')) then
        List.Add(IncludeTrailingPathDelimiter(directory) + sr.Name) ;
    until FindNext(sr) <> 0;
  finally
    SysUtils.FindClose(sr) ;
  end;
end;
Usage example 1:
GetSubDirectories('c:\', Memo1.Lines) ;
Usage example 2:
var
  sl : TStringList;
begin
  sl := TStringList.Create;
  try
    GetSubDirectories('c:\', sl) ;

    ShowMessage('Number of subfolders in "c:\": ' + IntToStr(sl.Count)) ;
  finally
    FreeAndNil(sl) ;
  end;
end;
Note: this function will not recurse subdirectories - it will only return a list of sub folder on the "first" level.

More on directories: Directory Related Delphi Functions and Procedures

Delphi tips navigator:
» Programmatically Fix the TabOrder property in your Delphi applications
« Dirty Delphi Localization: Hijack consts.pas to have Country / Language Specific Messages

More Delphi Programming Quick Tips
Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2008 Tips
  7. Get Subdirectories of a specified Directory from Delphi

©2009 About.com, a part of The New York Times Company.

All rights reserved.