我想在Inno Setup中以给定的文件扩展名计数目录中的文件。我写了下面的代码:
问候,
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;
用法可以是:
Log(IntToStr(AmountOfFilesInDir(ExpandConstant('{sys}*'), '.exe')));
我喜欢减少这个函数代码中的行数,使它看起来更专业,因为它看起来有点长。我需要知道如何在不失败的情况下做到这一点。
FindFirst
函数可自行根据通配符(扩展名)选择文件:
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;
使用方式:
Log(IntToStr(AmountOfFiles(ExpandConstant('{sys}*.exe'))));