簡體   English   中英

使用 VS2010 運行 StyleCop 時出現 CA2000 Microsoft.Reliability 錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM