使用VS2010运行StyleCop时出现CA2000 Microsoft.Reliability错误

时间:2011-05-23 18:00:34

标签: c# visual-studio visual-studio-2010 stylecop

使用此文件编写代码

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.

代码有什么问题?

ADDED

当我使用没有文化信息的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()); 
}

1 个答案:

答案 0 :(得分:4)

它警告您,您正在创建IDisposable的实例,该实例仅用于该函数并且未正确调用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)
{
  ...
}