Search code examples
delphidelphi-7

How to Search a File through all the SubDirectories in Delphi


I implemented this code but again i am not able to search through the subdirectories .

     procedure TFfileSearch.FileSearch(const dirName:string);
     begin
//We write our search code here
  if FindFirst(dirName,faAnyFile or faDirectory,searchResult)=0 then
  begin
    try
      repeat
      ShowMessage(IntToStr(searchResult.Attr));
        if (searchResult.Attr and faDirectory)=0 then   //The Result is a File
        //begin
          lbSearchResult.Items.Append(searchResult.Name)
         else 
         begin
            FileSearch(IncludeTrailingBackSlash(dirName)+searchResult.Name);
           //
         end;
       until FindNext(searchResult)<>0
     finally
     FindClose(searchResult);
     end;
   end;
   end;
    procedure TFfileSearch.btnSearchClick(Sender: TObject);
   var
 filePath:string;
begin
lbSearchResult.Clear;
if Trim(edtMask.Text)='' then
  MessageDlg('EMPTY INPUT', mtWarning, [mbOK], 0)
else
begin
  filePath:=cbDirName.Text+ edtMask.Text;
  ShowMessage(filePath);
  FileSearch(filePath);

end;

end;

I am giving the search for *.ini files in E:\ drive. so initially filePath is E:*.ini. But the code does not search the directories in E:\ drive. How to correct it?

Thanks in Advance


Solution

  • You can't apply a restriction to the file extension in the call to FindFirst. If you did so then directories do not get enumerated. Instead you must check for matching extension in your code. Try something like this:

    procedure TMyForm.FileSearch(const dirName:string);
    var
      searchResult: TSearchRec;
    begin
      if FindFirst(dirName+'\*', faAnyFile, searchResult)=0 then begin
        try
          repeat
            if (searchResult.Attr and faDirectory)=0 then begin
              if SameText(ExtractFileExt(searchResult.Name), '.ini') then begin
                lbSearchResult.Items.Append(IncludeTrailingBackSlash(dirName)+searchResult.Name);
              end;
            end else if (searchResult.Name<>'.') and (searchResult.Name<>'..') then begin
              FileSearch(IncludeTrailingBackSlash(dirName)+searchResult.Name);
            end;
          until FindNext(searchResult)<>0
        finally
          FindClose(searchResult);
        end;
      end;
    end;
    
    procedure TMyForm.FormCreate(Sender: TObject);
    begin
      FileSearch('c:\windows');
    end;