I have lots of code like this:
FileStream fs = File.Open(@"C:\Temp\SNB-RSS.xml", FileMode.Open);
using (XmlTextReader reader = new XmlTextReader(fs))
{
/* Some other code */
}
This gives me the following Code Analysis warning:
CA2000 : Microsoft.Reliability : In method 'SF_Tester.Run()', object 'fs' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'fs' before all references to it are out of scope.
If I follow the suggestion and I put the File.Open in a using statement, I get this:
CA2202 : Microsoft.Usage : Object 'fs' can be disposed more than once in method 'SF_Tester.Run()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 39
I'm using VS2010 and I can't help but think I'm doing something wrong but I don't see it. What am I doing wrong?
Sigh, exhausting isn't it. Avoid all this by using the recommended Create() method:
using (var reader = XmlReader.Create(@"C:\Temp\SNB-RSS.xml")) {
//...
}
As nobody provided a solution that solves this issue yet, I'm writing my working solution down here:
FileStream fs = new FileStream(fileName, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite);
try
{
using (var fileWriter = new StreamWriter(fs, encoding))
{
fs = null;
fileWriter.Write(content);
}
}
finally
{
if (fs != null)
fs.Dispose();
}
This removes CA2000.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With