Mega Code Archive

 
Categories / Delphi / Examples
 

How do i recurse sub directories

Question: How do I recurse sub directories? Answer: You will need to use Delphi's FindFirst() and FindNext() procedures to create a list of all the sub directories in a directory. For each sub directory, you will need to use Delphi's FindFirst() and FindNext() procedures, again to add any sub directories of the found directories to the list. Continue working down the list until all the directories have been processed. Example: procedure GetDirectories(const DirStr : string; ListBox : TListBox); var DirInfo: TSearchRec; r : Integer; begin r := FindFirst(DirStr + '\*.*', FaDirectory, DirInfo); while r = 0 do begin Application.ProcessMessages; if ((DirInfo.Attr and FaDirectory = FaDirectory) and (DirInfo.Name <> '.') and (DirInfo.Name <> '..')) then ListBox.Items.Add(DirStr + '\' + DirInfo.Name); r := FindNext(DirInfo); end; SysUtils.FindClose(DirInfo); end; procedure GetFiles(const DirStr : string; ListBox : TListBox); var DirInfo: TSearchRec; r : Integer; begin r := FindFirst(DirStr + '\*.*', FaAnyfile, DirInfo); while r = 0 do begin Application.ProcessMessages; if ((DirInfo.Attr and FaDirectory <> FaDirectory) and (DirInfo.Attr and FaVolumeId <> FaVolumeID)) then ListBox.Items.Add(DirStr + '\' + DirInfo.Name); r := FindNext(DirInfo); end; SysUtils.FindClose(DirInfo); end; procedure TForm1.FormCreate(Sender: TObject); var i : integer; begin ListBox1.Items.Clear; ListBox2.Items.Clear; ListBox1.Items.Add('C:\Delphi'); GetDirectories('C:\Delphi', ListBox1); i := 1; while i < ListBox1.Items.Count do begin GetDirectories(ListBox1.Items[i], ListBox1); Inc(i); end; end; procedure TForm1.ListBox1Click(Sender: TObject); begin ListBox2.Clear; GetFiles(ListBox1.Items[ListBox1.ItemIndex], ListBox2); end; Note: Recursing directories can take up a lot of memory. It is suggested that you consider creating a linked list or a temporary file to store your list entries instead of using a component (such as a Memo or StringList), as there are limits to the number of entries these components can have.