You are on page 1of 2

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.

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

You might also like