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

标签 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 */
}

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

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.

如果我按照建议将 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

我正在使用 VS2010,我忍不住认为我做错了什么,但我没有看到它。 我做错了什么?

最佳答案

唉,累不累啊。使用推荐的 Create() 方法可以避免这一切:

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

关于C#CA2000 :Dispose objects before losing scope using FileStream/XmlTextReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3128446/

相关文章:

c# - 在 C# 中从 Firebase 反序列化 JSON 对象

c++ - 为什么调用 GC.Collect 会加快速度

c# - 通过引用传递 IDisposable 对象会导致错误?

C++ 使用别名访问嵌套类型(使用 vs typedef)

c++ - 如何使用 'using' 指令分割循环依赖

c# - 在 LINQ 查询中使用动态数据类型

c# - 从另一个线程在 webbrowser 中加载大型 html 文件

c# - 我应该将 WCF 用于简单的文本有线协议(protocol)吗?

ios - 在哪里/如何手动处理 WKWebView estimatedProgress 的观察者

c++ - 调用基类构造函数的 "Using"关键字