Delphi Text file not found

160 Views Asked by At

I saved my text file in the same folder as my Delphi project but when I test if the file exists, it still says it does not exist. I've tried everything I know of what I could find on the web but nothing works.

Can anyone tell me what the problem could be?

This is the current code:

var
  iMessage, iCount: integer;
  mFile: Textfile;
  sLine: string;     
begin
  iMessage := MessageDlg('Save receipt to ' + arrMonth[1], mtCustom,
    [mbYes, mbNo, mbCancel], 0);
  if iMessage = mrYes then
  begin
    AssignFile(mFile, 'Receipts.txt');
    if NOT FileExists('Receipts.txt') then
    begin
      ShowMessage('File does not exist');
    end;
    Append(mFile);
    for iCount := 0 to redReceipt.Lines.Count - 1 DO
    begin
      sLine := redReceipt.Lines[iCount];
      Writeln(mFile, sLine);
    end;
    Writeln(mFile, '////////////////');
    CloseFile(mFile);
  end;
1

There are 1 best solutions below

1
SilverWarior On

The reason why your application does not find your file is because you are not specifying a full path to the file. Your application is trying to find such file in CurrentDir which may not be the same directory that your application executable is in.

For instance, if your application is launched from a shortcut, from the very start the CurrentDir will be the same directory that was set as the Working Directory of that shortcut.

But, bear in mind that CurrentDir can change during the execution of your application. For instance, using certain dialog boxes can change it.

So, if you are searching for files whose location is relative to the location of your executable, you first need to retrieve the location of your executable using TApplication.ExeName in VCL, or using ParamStr(0) in FMX.

You can then use that information when creating a full path of the desired file. Here is an example for VCL:

FileName := ExtractFilePath(Application.ExeName)+'Receipts.txt';
AssignFile(mFile, FileName);