For one of my applications I needed a function to determine if a directory, and optionally its sub directories, had at least one file with a certain file extension. So I wrote one myself, hopefully someone can use this.
FoundFiles := DirectoryHasTheseFiles(Dirname, '*.ext1,*ext2;', true);
aDir is a directory (regular filename would not be checked!).
SearchMask is your typical mask '*.ext1;*.ext2;*.ext3;'.
CheckSubDirs is a boolean to set if sub directories should be searched as well.
As soon as a matching file has been found, the search stops and exits with a positive outcome (true).
If no matching file was found, the result will be false.
Note: Uses sysutils unit.
function DirectoryHasTheseFiles(aDir:string; SearchMask:string; checkSubDirs:boolean):boolean;
var
SearchRecResult: TSearchRec;
FoundAFile: boolean;
function ValidExtension:Boolean;
begin
Result := (pos('*'+ExtractFileExt(SearchRecResult.Name)+';', SearchMask)>0);
end;
begin
SearchMask := SearchMask+';'; // in case the list doesn't end with a ";"
FoundAFile := FindFirst(IncludeTrailingPathDelimiter(aDir) + '*', faAnyFile, SearchRecResult) = 0;
Result := False;
while FoundAFile and not(Result) do
begin
// Found a matching extensions that is not a directory
if not(DirectoryExists(IncludeTrailingPathDelimiter(aDir)+SearchRecResult.Name)) and ValidExtension then
begin
Result := true;
break;
end;
// if checkSubDirs search subdirs are not . or ..
if checkSubDirs and
( SearchRecResult.Name<>'.') and
( SearchRecResult.Name<>'..') and
DirectoryExists(IncludeTrailingPathDelimiter(aDir)+SearchRecResult.Name) then
begin
if DirectoryHasTheseFiles(IncludeTrailingPathDelimiter(aDir)+SearchRecResult.Name, SearchMask, checkSubDirs) then
begin
Result := true;
break;
end;
end;
FoundAFile := FindNext(SearchRecResult)=0;
end;
FindClose(SearchRecResult);
end;
This topic was modified 9 hours ago 3 times by
Hans