C# CA2000:Dispose objects before losing scope using FileStream/XmlTextReader

The Diamond Z picture The Diamond Z · Jun 27, 2010 · Viewed 9.8k times · Source

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?

Answer

Hans Passant picture Hans Passant · Jun 27, 2010

Sigh, exhausting isn't it. Avoid all this by using the recommended Create() method:

 using (var reader = XmlReader.Create(@"C:\Temp\SNB-RSS.xml")) {
     //...
 }