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