I have a singleton-like class that can do some logging output:
class Foo
{
private static Foo instance;
private System.IO.StreamWriter os;
private Foo()
{
this.os = System.IO.File.CreateText( "D:/tmp/test" );
}
public static Foo Instance
{
get
{
if ( instance == null )
instance = new Foo();
return instance;
}
}
public void Log( string s )
{
os.Write( s );
}
}
When I use that in a sample program like
class Program
{
private static void Main( string[] args )
{
Foo.Instance.Log( "asdf\n" );
}
}
the file is being created, but no output is written. I assume this is because the StreamWriter
has never been flushed.
I tried to repair the class by calling to Close()
in ~Foo()
:
~Foo()
{
os.Close();
}
but this yields a ObjectDisposedException
. Apparently Foo.os
has already been disposed when Foo
's destructor is called.
How do I ensure that my StreamWriter
is flushed "at last"?
EDIT
Setting this.os.AutoFlush = true;
works. Adding a Flush()
method to Foo
and calling it in appropiate places does as well, but I'm interested if there any way of doing without.