C#CA2000:使用FileStream/XmlTextReader在丢失范围之前处置对象

The*_*d Z 8 c# dispose using ca2000 ca2202

我有很多像这样的代码:

FileStream fs = File.Open(@"C:\Temp\SNB-RSS.xml", FileMode.Open); 
using (XmlTextReader reader = new XmlTextReader(fs)) 
{ 
   /* Some other code */
}
Run Code Online (Sandbox Code Playgroud)

这给了我以下代码分析警告:

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.
Run Code Online (Sandbox Code Playgroud)

如果我按照建议操作并将File.Open放在using语句中,我会得到:

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
Run Code Online (Sandbox Code Playgroud)

我正在使用VS2010而且我不禁想到我做错了什么但是我没有看到它.我究竟做错了什么?

Han*_*ant 15

叹气,筋疲力尽吧.通过使用推荐的Create()方法避免所有这些:

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


tes*_*ino 11

由于没有人提供解决此问题的解决方案,我正在编写我的工作解决方案:

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();
 }
Run Code Online (Sandbox Code Playgroud)

这将删除CA2000.