How to Open, Close, Read and Delete a File in Delphi XE2?
How to Open, Close, Read and Delete a File in Delphi XE2?
File Handling is very simple in delphi programming language. Here is a simple delphi program example for file handling. Following delphi program opens, writes and reads a file. After that the file is closed and finally deleted. Opening a file, reading / writing a file and deleting files are very common functionalities used in any delphi application. Following delphi program example for file handling does the same in very simple way.
procedure MyForm.HowToOpenCloseAndDeleteFile;
var
fileName : string;
myFile : TextFile;
data : string;
begin
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');
Write(myFile, 'Hello World');
// Close the file
CloseFile(myFile);
CloseFile(myFile);
// Reopen the file in read mode
Reset(myFile);
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
ReadLn(myFile, data);
ShowMessage(data);
end;
while not Eof(myFile) do
begin
ReadLn(myFile, data);
ShowMessage(data);
end;
// Close the file for the last time
CloseFile(myFile);
CloseFile(myFile);
// Now delete the file
if DeleteFile(fileName) then ShowMessage(fileName+' deleted')
else ShowMessage(fileName+' not deleted');
if DeleteFile(fileName) then ShowMessage(fileName+' deleted')
else ShowMessage(fileName+' not deleted');
end;