is Directory empty

From Lazarus wiki
Jump to navigationJump to search

Template:is Directory Empty


Return to the page Code Beispiele.


The following function determines whether a directory is empty on both Windows and Linux:

uses
  SysUtils;

  ...

function IsDirectoryEmpty(Directory: string): boolean;
var
  SearchRec: TSearchRec;
  I: integer;
begin
  Result := False;

  FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', faAnyFile, SearchRec);

  for I := 1 to 2 do
    if (SearchRec.Name = '.') or (SearchRec.Name = '..') then
      Result := FindNext(SearchRec) <> 0;

  FindClose(SearchRec);
end;


Example Usage on Windows:

function Test: string;
begin
  if IsDirectoryEmpty('D:\Test') then
    Result := 'Empty'
  else
    Result := 'Not Empty';
end;

Example Usage on Linux:

function Test: string;
begin
  if IsDirectoryEmpty('/home/user/Test') then
    Result := 'Empty'
  else
    Result := 'Not Empty'; 
end;