使用此文件编写代码
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());
}
答案 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)
{
...
}