Get Subdirectories of a specified Directory

Submitted by:Jhon Smith

Date added:17 September, 2011

Category:Delphi

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.

Tags: get subdirectories

Code Snippet:

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;
 
 

Comments