I have a very simple logging mechanism in my application which periodically writes a line to a file (a logging library would be overkill for my needs) which looks something like this:
private string logfile = @"C:\whatever.log";
public void WriteLine(string line)
{
using(FileStream fs = File.Open(logfile, FileMode.Append))
{
// Log Stuff
}
}
So any time I call that method, a new FileStream is created and disposed after logging is finished. So I considered using an already instantiated object to prevent the continuous creation of new objects:
private string logfile = @"C:\whatever.log";
private FileStream myStream = File.Open(logfile, FileMode.Append);
public void WriteLine(string line)
{
using(myStream)
{
// Log Stuff
}
}
However, the MSDN reference discourages this (last example), due to scope issues. What does one do in that case? Is the overhead in my first example negligible?
The using
statement doesn't do anything else than calling the Dispose()
method of the object.
So considering your second example, after the first call to the WriteLine(string)
method the filestream is disposed. So any other call, after the first one, to this Method will result in an exception.
Using the File.AppendText()
method like Chris had suggested in the comment would be a way to go. But keep in mind, that using this or any other File...
method will also open a stream and close and dispose it afterwards.
It will just result in less code.