Get Subdirectories of a specified Directory

Submitted by:Andery Smith

Date added:29 April, 2012

Category:Delphi

This function will not recurs subdirectories - it will only return a list of sub folder on the "first" level.

Tags: get subdirectories

Code Snippet:

 //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