Skip to main content
 首页 » 编程设计

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

2024年02月23日20JeffreyZhao

用这个文件写代码,

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 的实例,该实例仅与该函数一起使用,并且未正确调用 Dispose。这是由于您使用了 FileStream 实例。解决这个问题的正确方法是使用 using block

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) 
{ 
  ... 
}