To search for specific files on your harddisk, use findfirst and findnext as wodzu said.
This is easy if you just want to search in one directory.
A call of FindFirst searches for the first file and FindNext within a repeat-clause will search for every follwing files.
The following code capsulates the functionality to search recursively in all subdirectories too!
The procedure needs 5 parameters:
- Directory (e.g. 'C:\Programs')
- Searchmask (e.g. '*.*' or '*.doc', in your case *.uj)
- a list where to store the filenames (e.g. Listbox1.Items)
- recursive search (True searches all subdirs recursively, false searches only in the parameter-directory).
- ClearList lets the List be cleared before the new filenames are attached.
Code:
procedure GetFilesInDirectory(Directory: String; const Mask: String;
List: TStrings;
WithSubDirs, ClearList: Boolean);
procedure ScanDir(const Directory: String);
var
SR: TSearchRec;
begin
if FindFirst(Directory + Mask, faAnyFile and not faDirectory, SR) = 0 then try
repeat
List.Add(Directory + SR.Name)
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
if WithSubDirs then begin
if FindFirst(Directory + '*.*', faAnyFile, SR) = 0 then try
repeat
if ((SR.attr and faDirectory) = faDirectory) and
(SR.Name <> '.') and (SR.Name <> '..') then
ScanDir(Directory + SR.Name + '\');
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
end;
end;
begin
List.BeginUpdate;
try
if ClearList then
List.Clear;
if Directory = '' then Exit;
if Directory[Length(Directory)] <> '\' then
Directory := Directory + '\';
ScanDir(Directory);
finally
List.EndUpdate;
end;
end;
Here is an example how to call the procedure:
Code:
procedure TForm1.Button1Click(Sender: TObject);
begin
GetFilesInDirectory('C:\', '*.*', Listbox1.Items, False, True);
end;
In this example all filenames (*.*) in the directory 'C:\' are stored in 'Listbox1.Items'. Subdirectories are not searched (False).
You can now easily add your own functionalities at the position where the files are added to the list:
Code:
List.Add(Directory + SR.Name)
I hope this helps.
Note that the code and parts of the explanation are copied from a forum. I just translated it for your understanding.
Greetings,
Dirk
Bookmarks