gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:03:44 26 4
gpt4 key购买 nike

我有很多这样的代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com