C#CA2000:使用的FileStream / XmlTextReader的失去范围之前释放对象 [英] C# CA2000:Dispose objects before losing scope using FileStream/XmlTextReader
本文介绍了C#CA2000:使用的FileStream / XmlTextReader的失去范围之前释放对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多这样的代码:
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.
如果我按照建议,我把File.Open在using语句,我得到这个:
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
我使用VS2010,我不禁觉得我做错了什么,但我没有看到它。
我在做什么错了?
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?
推荐答案
感叹,倾尽是不是。避免这一切都通过使用推荐的Create()方法:
Sigh, exhausting isn't it. Avoid all this by using the recommended Create() method:
using (var reader = XmlReader.Create(@"C:\Temp\SNB-RSS.xml")) {
//...
}
这篇关于C#CA2000:使用的FileStream / XmlTextReader的失去范围之前释放对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文