DelphiBasics
FileExists
Function
Returns true if the given file exists SysUtils unit
 function FileExists(const FileName string):Boolean;
Description
The FileExists function returns True if the given FileName file exists.
 
The file is searched for in the current directory.
 
False may be returned if the user is not authorised to see the file.
Related commands
FileSearchSearch for a file in one or more directories
FileSizeGives the size in records of an open file
FileGetAttrGets the attributes of a file
FileSetAttrSets the attributes of a file
 Download this web site as a Windows program.




 
Example code : Check for a file before and after deleting it
var
  fileName : string;
  myFile   : TextFile;
  data     : string;

begin
  // Try to open a text file for writing to
  fileName := 'Test.txt';
  AssignFile(myFile, fileName);
  ReWrite(myFile);

  // Write to the file
  Write(myFile, 'Hello World');

  // Close the file
  CloseFile(myFile);

  // Reopen the file in read mode
  Reset(myFile);

  // Display the file contents
  while not Eof(myFile) do
  begin
    ReadLn(myFile, data);
    ShowMessage(data);
  end;

  // Close the file for the last time
  CloseFile(myFile);

  // Now see if the file exists
  if FileExists(fileName)
  then ShowMessage(fileName+' exists OK')
  else ShowMessage(fileName+' does not exist');

  // Delete the file and look again
  DeleteFile(fileName);
  if FileExists(fileName)
  then ShowMessage(fileName+' still exists!')
  else ShowMessage(fileName+' no longer exists');
end;
Show full unit code
  Hello World
  Test.txt exists OK
  Test.txt no longer exists
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page