I wanted to count files in a directory with a given file extension in Inno Setup. I wrote the following code.
Regards,
function AmountOfFilesInDir(const DirName, Extension: String): Integer;
var
FilesFound: Integer;
ShouldBeCountedUppercase, ShouldBeCountedLowercase: Boolean;
FindRec: TFindRec;
begin
FilesFound := 0;
if FindFirst(DirName, FindRec) then begin
try
repeat
if (StringChangeEx(FindRec.Name, Lowercase(Extension), Lowercase(Extension), True) = 0) then
ShouldBeCountedLowercase := False
else
ShouldBeCountedLowercase := True;
if (StringChangeEx(FindRec.Name, Uppercase(Extension), Uppercase(Extension), True) = 0) then
ShouldBeCountedUppercase := False
else
ShouldBeCountedUppercase := True;
if (FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0)
and ((ShouldBeCountedUppercase = True) or (ShouldBeCountedLowercase = True)) then begin
FilesFound := FilesFound + 1;
end;
until not FindNext(FindRec);
finally
FindClose(FindRec);
end;
end;
Result := FilesFound;
end;
And an usage example can be:
Log(IntToStr(AmountOfFilesInDir(ExpandConstant('{sys}\*'), '.exe')));
I like to reduce the lines in this function's code to make it look more professional as it looks bit long. I need to know how can I do it without failing this function.
Thanks in advance.
The FindFirst
function can select the files based on wildcard (extension) on its own:
function AmountOfFiles(PathWithMask: string): Integer;
var
FindRec: TFindRec;
begin
Result := 0;
if FindFirst(PathWithMask, FindRec) then
begin
try
repeat
Inc(Result);
until not FindNext(FindRec);
finally
FindClose(FindRec);
end;
end;
end;
Use it like:
Log(IntToStr(AmountOfFiles(ExpandConstant('{sys}\*.exe'))));