How can I find all MP3 files in a directory?
Question
I recently started with delphi and now I want to get all mp3 files from a directory. I want something like the php function glob().
Solution
The old way of doing it is approx:
var
status : dword;
sr : TSearchRec;
begin
status := FindFirst('*.mp3',faAnyFile,sr);
while status = 0 do
begin
// sr.Name is the filename; add it to a list
// or something. Note there is no path so you
// may need to add that back on somewhere
status := FindNext(sr);
end;
SysUtils.FindClose(sr);
// ...
end;
OTHER TIPS
Try IOUtils.TDirectory.
If additional libraries are ok for you, take a look at the Jedi Code Library.
In unit common\JclFileUtils, there is a compact helper function:
function BuildFileList(const Path: string;
const Attr: Integer; const List: TStrings;
IncludeDirectoryName: Boolean = False): Boolean;
The JCL is well maintained and includes great extensions and some IDE improvements. The (very easy to use) JCL installer is available at http://sourceforge.net/projects/jcl/
The ancient TFileListBox in the Delphi FileCtrl unit is a good solution.
It has been there since Delphi 1, and About Delphi has a nice example on how to use it.
You can drop it on a form, set Visible = False
, and never worry about it.
It supports filtering (for instance on extension), so it will work very nicely with your *.mp3 criterion.
--jeroen
a very nice free component is TFindFile at Delphi Area: http://www.delphiarea.com/products/delphi-components/findfile/
it will give you complete control over searching for files/folders, threaded or non