Mega Code Archive

 
Categories / Delphi / Files
 

Search for a File in a Tree

Title: Search for a File in a Tree Question: In article (ID 2358) by Adam Lanzafame he explains how to search for a file in a tree by using imagehlp.dll. This worked for most files, but seems to fail when searching for a file that lives in the windows directory (in W2000 anyway). Try searching for actmovie.exe, which resides in .\WinNt\system32. I get nothing returned. The function call is useful though, so I decided to implement it using native Delphi code. The function SearchTree takes parms AStartDir : string (where to start search eg. 'C:\') AFileToFind : string (file name to find) The function returns full path/filename if found and '' if not. Answer: // ================================================== // Recursive Search for a file starting in AStartDir // Result is FULL Path/Filename if found // else NULLSTR is returned. // ================================================== function SearchTree(const AStartDir,AFileToFind : string) : string; var sResult : string; // Recursive Dir Search procedure _SearchDir(const ADirPath : string); var rDirInfo : TSearchRec; sDirPath : string; begin sDirPath := IncludeTrailingPathDelimiter(ADirPath); if FindFirst(sDirPath + '*.*',faAnyFile,rDirInfo) = 0 then begin // First find is a match ? if SameText(rDirInfo.Name,AFileToFind) then sResult := sDirPath + rDirInfo.Name; // Traverse Starting Path while (sResult = GENERAL_NULLSTR) and (FindNext(rDirInfo) = 0) do begin if SameText(rDirInfo.Name,AFileToFind) then sResult := sDirPath + rDirInfo.Name else // Recurse Directorty ? if (rDirInfo.Name '.') and (rDirInfo.Name '..') and ((rDirInfo.Attr and faDirectory) = faDirectory) then _SearchDir(sDirPath + rDirInfo.Name); end; FindClose(rDirInfo); end; end; // SearchTree begin Screen.Cursor := crHourGlass; sResult := ''; _SearchDir(AStartDir); Screen.Cursor := crDefault; Result := sResult; end;