使用此文件编写代码,
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());
}发布于 2011-05-24 02:02:15
它警告你,你正在创建一个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)
{
...
}https://stackoverflow.com/questions/6101024
复制相似问题