Jan Doggen
Jan Doggen

Reputation: 9106

TStreamWriter (Auto)Flush does not?

Despite what is said in Text File Writing performances in Delphi (comments under Ken White's answer), I see the TStreamWriter not flushing with the following code:

procedure TFrmAddEvents.LogEvent(AEvent: TcxSchedulerEvent);
begin
   if not Assigned(FStreamWriter) then
   begin
      FStreamWriter := TStreamWriter.Create(TFileStream.Create(ChangeFileExt(ParamStr(0),'.log'),fmCreate or fmOpenRead));
      FStreamWriter.AutoFlush := true;
   end;
   FStreamWriter.WriteLine(TcxEventDescription(AEvent));
   // Even this has no effect:
   FStreamWriter.Flush;
end;

Even after executing the

if Assigned(FStreamWriter) then FStreamWriter.Free;    

in FormClose, the file is still 0 bytes.
When the program has finished executing, the file is 600+ kB.

What can be going on and how to fix?

[Edited 7. Jan 2014]

Updated code after Uwe's answer; still does not work:

procedure TFrmAddEvents.LogEvent(AEvent: TcxSchedulerEvent);
var lName: string;
begin
   lName := ChangeFileExt(ParamStr(0),'.log');
   if not Assigned(FStreamWriter) then
   begin
      FStreamWriter := TStreamWriter.Create(lName); // Or TStreamWriter.Create(lName,true);
      FStreamWriter.AutoFlush := true;
   end;
   FStreamWriter.WriteLine(TcxEventDescription(AEvent));
   // Next does not help either:
   FStreamWriter.Flush;
end;

Until I call FStreamWriter.Free the file remains 0 bytes.

Upvotes: 2

Views: 1747

Answers (1)

Uwe Raabe
Uwe Raabe

Reputation: 47819

The TStreamWriter flushing means it will just write its buffer to the attached stream. This does not necessary mean that any TFileStream will flush its OS buffers, just because the TStreamWriter doesn't know of any TFileStream (only TStream).

To make it worse, you are giving a TFileStream instance created by your own. So TStreamWriter doesn't take ownership of the stream and thus will not free it on Destroy. The freeing of the stream would however close the file and thus write the content to disk.

Upvotes: 3

Related Questions