Check if a directory is empty in delphi

Check if a directory is empty in delphi

// This function returns true if Directory is an empty directory

function DirectoryIsEmpty(Directory: string): Boolean;
var
SR: TSearchRec;
i: Integer;
begin
Result := False;
FindFirst(IncludeTrailingPathDelimiter(Directory) + ‘*’, faAnyFile, SR);
for i := 1 to 2 do
if (SR.Name = ‘.’) or (SR.Name = ‘..’) then
Result := FindNext(SR) <> 0;
FindClose(SR);
end;

// ——–
// Example:
// ——–

procedure TForm1.Button1Click(Sender: TObject);
begin
if DirectoryIsEmpty(‘C:\test’) then
Label1.Caption := ’empty’
else
Label1.Caption := ‘not empty’;
end;