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
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
 Author links

 Buy Website Traffic at

 Buy Proxies at
 Download this web site as a Windows program.

Example code : Searching in the current directory and beyond
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
  SysUtils,   // Unit containing the FileSearch command
  Forms, Dialogs;
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
Form1: TForm1;
{$R *.dfm} // Include form definitions
procedure TForm1.FormCreate(Sender: TObject);

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