[D7 Newbie] Exception while closing busy file



Hi,

I'm still pretty wet behind the ears when it comes to Delphi,
so the problem below might be very simple to solve for more
experienced Delphi developers.

I'd like to show a form with a push button to launch an operation. But
the same button should then be available to stop and close the
application:

---------------- START ----------------
procedure TForm1.Button1Click(Sender: TObject);
var
log : TextFile;
current : TFileStream;
i : Integer;
status : String;

begin
//Check if user clicked to stop app
If Label1.Caption = 'Run!' then begin
try
current.Free;
CloseFile(log);
finally
Close;
//Can't use in exceptions Exit;
end;
end;

//Init string to output, and create files
status := 'test';

AssignFile(log, 'log.txt');
ReWrite(log);

current := TFileStream.Create('current.txt',fmCreate);

//Just a dummy loop to check that I can close the app
//while the loop is running
For i := 1 to 100000 do begin
Application.ProcessMessages;

Label1.Caption := IntToStr(i);
current.Write(Pointer(status)^,Length(status));
//Flush(current);
current.Seek(0, soFromBeginning);

WriteLn(log, IntToStr(i));
end;

current.Free;
CloseFile(log);

end;
---------------- END ------------------------

When clicking, I get : "Project Project1.exe raised exception class
EInOutError with message 'I/O Error 32'. Process stopped.". I assume
Delphi won't let me close a file while a write operation is being done
in the For loop.

Does anyone know how to solve this?

Thank you for any tip
P.
.