![](/img/trans.png)
[英]CA2000 : Microsoft.Reliability object is not disposed along all exception paths
[英]CA2000 Microsoft.Reliability error when running StyleCop with VS2010
用这个文件写代码,
try
{
FileStream aFile = new FileStream(doFilePath, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(templateString, fileNameList, topLevelTestbench);
sw.Close();
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown! {0}", doFilePath);
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
我在 StyleCop 中收到此错误消息。
Error 6 CA2000 : Microsoft.Reliability :
In method 'DoFile.Generate(string, string, string)', call System.IDisposable.Dispose
on object 'aFile' before all references to it are out of scope.
代码可能有什么问题?
当我使用没有文化信息的 Format 方法时,StyleCop 再次出现错误。 拥有此代码使其工作。
using System.Globalization;
try
{
string line = String.Format(CultureInfo.InvariantCulture, templateString, fileNameList, topLevelTestbench);
File.AppendAllText(doFilePath, line);
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown! {0}", doFilePath);
Console.WriteLine(e.ToString());
}
它警告您,您正在创建一个IDisposable
实例,该实例仅在 function 中使用,并且未正确调用Dispose
。 这是由于您使用了FileStream
实例。 解决此问题的正确方法是使用using
块
using (FileStream aFile = new FileStream(doFilePath, FileMode.OpenOrCreate)) {
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(templateString, fileNameList, topLevelTestbench);
sw.Close();
}
编辑
注意:更简单的方法是使用File.AppendAllText
。
try
{
var line = String.Format(templateString, fileNameList, topLevelTestbench);
File.AppendAllText(doFilePath, line);
}
catch (IOException e)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.