I want to create a .txt file and write to it at any moment at run-time. To do this, I'm using the AssignFile() function. But I am having trouble in instances where my file already exists. I get an error that says: File access denied.
To better explain, see these two examples:
Ex1: if I call AssignFile() the first time when the file does not exist, OK! But, if the file exists, this does not work.
Ex2: if I call AssignFile() the second time (when AssignFile() was successful the first time), this also does not work.
Is this a bug in the AssignFile() function?
var
myfile: TextFile;
Procedure WriteFileContent(const MyTxtFile: string; MyNumber: DWORD);
var
F: TextFile;
Begin
If FileExists(MyTxtFile) Then
Begin
AssignFile(F, MyTxtFile);
Rewrite(F);
Writeln(F, '0x' + IntToHex(MyNumber,8));
CloseFile(F);
End;
End;
begin
try
// Calling AssignFile() by first time
AssignFile(myfile, 'myfile.txt');
Rewrite(myfile);
CloseFile(myfile);
setfileattributes('myfile.txt', FILE_ATTRIBUTE_HIDDEN);
Sleep(5000);
// Calling AssignFile() by second time
WriteFileContent('myfile.txt', 123456789);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.