[Mono-list] Buffering for StreamWriter

Miguel de Icaza miguel@ximian.com
16 May 2002 12:20:23 -0400


> I always call Flush() on StreamWriter before calling Close().  Is that
> unnecessary?  And if you Flush() but don't Close(), is the file properly
> closed anyway when the StreamWriter goes out of scope?

My guess is that the file will not be closed when the StreamWriter goes
out of scope (unless we add ourselves a destructor, but even then, I am
not sure if the GC system will guarantee that the destructor will be
invoked).

For classes that implement IDisposable (like StreamWriter), you have to
call the Dispose method (or you can manually call close in this case) to
make sure that their resources are released (in this case an OS file
handle is the precious resource).

You can use the `using' statement in C# to do this for you:

	using (f = new StreamWriter (...)){
		...
	}

That will make sure that the file is properly disposed/flushed (if you
return, if there is an exception, or if you just leave the block; the
file will be released).

Miguel