Just ran a code analysis on one of the applications I inherited, and it raised warnings about code similar to the following:
using (StreamWriter tw = File.AppendText("Log.txt"))
{
try
{
tw.WriteLine(DateTime.Now.ToString("------------------------");
tw.WriteLine(data);
}
catch(Exception ex)
{
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "Error writing to the log file: {0}", ex.Message));
}
finally
{
tw.Close();
}
}
If I comment out the finally
block, the warning is not raised. I was under impression that closing a stream writer only closed the underlying file, but did not actually dispose of the writer object. Is code analysis broken, or am I misunderstanding how stream writer should be used?
Here's another example where code analysis complains about possible disposing of both writer and the underlying stream twice:
using (TextReader tr = new StreamReader(File.OpenRead(filename)))
{
while (tr.ReadLine() != null)
{
counter++;
}
tr.Close();
}
It complains about both tr
and File.OpenRead(filename)
Close just calls Dispose on the object, so yes, you're disposing of the object twice. (Not that disposing of an object twice is problematic, just redundant.)