How do I make FindFirst look for files in the current directory?

3.2k Views Asked by At

I'm having trouble writing code for a procedure that will open a directory folder and delete all of the files within it recursively so that I can in turn delete the folder itself. I won't have trouble with the recursive procedure, but I can't seem to get the FindFirst/FindNext/FindClose functions to work properly. The procedure below should search the current directory for any files of any type (however I may be misusing string wildcards; I didn't find much online about the syntax of their use).

procedure TForm1.Button1Click(Sender: TObject);
var SR: TSearchRec;
begin
 ShowMessage(GetCurrentDir);
 if (FindFirst('\*.*',faAnyFile,SR)=0) then
 begin
  repeat
   ShowMessage(SR.Name);
  until FindNext(SR)<>0;
  FindClose(SR);
 end
 else begin
  ShowMessage('No matching files found');
 end;
end;

Right now it seems that no matter what I put in for the filename, the procedure never finds any files and always returns the 'No matching files found' message.

1

There are 1 best solutions below

12
On

The path '\*.*' is relative to the root directory of the drive of the current working directory. You probably mean to pass GetCurrentDir + '\*' to FindFirst. Or even better, TPath.Combine(GetCurrentDir, '*').

For example, this program demonstrates that you code works correctly provided that you pass an appropriate path to FindFirst.

program FindFirstDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils, IOUtils;

var
  SR: TSearchRec;

begin
  Writeln(GetCurrentDir);
  if FindFirst(TPath.Combine(GetCurrentDir, '*'),faAnyFile,SR)=0 then
  begin
    repeat
      Writeln(SR.Name);
    until FindNext(SR)<>0;
    FindClose(SR);
  end;
  Readln;
end.