how to auto-update a text file before closing it

  • Thread starter Thread starter Fabian Härle
  • Start date Start date
F

Fabian Härle

Hi,

if I write to a tet file via a System.IO.TextWriter the changes to the file
are not done before I close the file. Is there a possibility to always save
the file with every change?
The point is that I want to write to my log file even if my app crashes. As
the log file is not closed clearly in such a case, all my information is
gone.

Regards + thanx very much in advance

Fabian
 
Fabian

You could call the TextWriter's Flush() method every time you write to it.

I assume you have a static method in a Log-class to write to you file? If
so, add a static Close or Terminate method that flushes the textwriter and
closes the file. You'll have to call this in the "finally"-part of a try
catch statement in your main() method.

HTH
Jako
 
Fabian Härle said:
Hi,

if I write to a tet file via a System.IO.TextWriter the changes to the
file are not done before I close the file. Is there a possibility to
always save the file with every change?
The point is that I want to write to my log file even if my app crashes.
As the log file is not closed clearly in such a case, all my information
is gone.

One way is to open and close the log file every time something is written
to it.

- Magnus
 
Magnus / Fabian

Although this will solve the problem, you should also consider the
performance implication of opening and closing a file that often. If you
(Fabian) don't write to the log very often, then this would make sense,
otherwise it will really slow things down.

Jako
 
Jako,

You're right, I should have pointed out that my solution is only suitable if
writing to the log file isn't a performance bottleneck.

- Magnus
 
I'm not sure what class you are using to write to your text file, but
StreamWriter has an AutoFlush property (saves you the trouble of making sure
you call Flush whenever you write).
 
Back
Top