Search for a file in one or more directories SysUtils unit
 function FileSearch(const FileName, DirectoryList string):string;
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!
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
FindCloseCloses a successful FindFirst file search
FindFirstFinds all files matching a file mask and attributes
FindNextFind the next file after a successful FindFirst
TSearchRecRecord used to hold data for FindFirst and FindNext
 Download this web site as a Windows program.

Example code : Searching in the current directory and beyond
  myFile       : TextFile;
  fileName     : string;
  fullFilePath : string;
  dir1, dir2   : string;

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

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

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

  // 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

  // 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');
Show full unit code
  Test.txt found OK
  C:\Program Files\Test.txt found OK
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page