SmartPascal
FileSearch
Function
Search for a file in one or more directories SysUtils unit
 function FileSearch ( const FileName, DirectoryList : string ) : string;
Description
The FileSearch function searches for the given FileName in the given DirectoryList.
 
The FileName may be a file name or sub-path to a file.
 
The DirectoryList is a ; separated list of directory (path) names.
 
If the file cannot be found, then an empty string is returned. Otherwise, the full path plus the name of the file is returned.
 
WARNING: the current directory (see GetCurrentDir) is ALWAYS searched first, regardless of the given directories. If the file is found there, then the returned path is Only the file name.
 
You have been warned!
Notes
If any of the specified directories do not exist, no error is thrown.

The directory list can be an empty string - only the current directory will be searched.
Related commands
FindClose Closes a successful FindFirst file search
FindFirst Finds all files matching a file mask and attributes
FindNext Find the next file after a successful FindFirst
TSearchRec Record used to hold data for FindFirst and FindNext
 
Example code : Searching in the current directory and beyond
var
  myFile       : TextFile;
  fileName     : string;
  fullFilePath : string;
  dir1, dir2   : string;

begin
  // The file we will be searching for
  fileName := 'Test.txt';

  // Write to a text file in the current directory
  AssignFile(myFile, fileName);
  ReWrite(myFile);
  Write(myFile, 'Hello World');
  CloseFile(myFile);

  // Write to a text file to another directory
  AssignFile(myFile, 'C:\Program Files\'+fileName);
  ReWrite(myFile);
  Write(myFile, 'Hello World');
  CloseFile(myFile);

  // Define two directories where we want to search for the file
  dir1 := 'C:\No such directory';
  dir2 := 'C:\Program Files';

  // Search for the file
  fullFilePath := FileSearch(fileName, dir1+';'+dir2);

  // If we search now, we will find it in the current directory
  if fullFilePath = ''
  then ShowMessage(fileName+' not found')
  else ShowMessage(fullFilePath+' found OK');

  // Now delete Test.txt from the current directory and retry
  DeleteFile(fileName);

  // If we search now, we will find it in one of the search dirs
  fullFilePath := FileSearch(fileName, dir1+';'+dir2);
  if fullFilePath = ''
  then ShowMessage(fileName+' not found')
  else ShowMessage(fullFilePath+' found OK');
end;
Show full unit code
   Test.txt found OK
   C:\Program Files\Test.txt found OK