I have a piece of code I use while debugging to write a line of information to a file.
private bool appendLine(string line2Write, string fileName)
{
try
{
StreamWriter tw;
using (tw = File.AppendText(fileName))
{
tw.WriteLine(line2Write);
tw.Close();
}
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show("Unable to write to: " + fileName + "\r\n" + ex.ToString() + "\r\n OK to retry", "File Sysytem Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (result == DialogResult.Cancel)
{
return false;
}
}
return true;
}
I don't want to leave the file open because, if it is debugging information I don't want to risk the last bit if the program crashes.
I am probably not understanding what the CA2202 is telling me.
Here's the whole error statement:
Warning CA2202 Object 'tw' can be disposed more than once in method 'familyFinances.appendLine(string, string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
"tw" only exists in this code. And, I've never had an error running it this way.
Options or suggestions?
You call
Close
andDispose
. You callClose
explicitly andDispose
implicitly trough theusing
statement. The two are equivalent, you should only have one of them.This will not throw the warning:
The rule description explicitly states that
Close
andDispose
are both consideredWhile in this case the object will not complain about the double dispose, there is no real reason to keep both, so it's still a good catch with regard to code style.