With this file write code,
try
{
FileStream aFile = new FileStream(doFilePath, FileMode.OpenOrCreate);
开发者_如何学JAVA 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;
}
I have this error message with 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.
What might be wrong with the code?
ADDED
I again got error from StyleCop when I use the Format method without culture info. Having this code made it work.
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());
}
It's warning you that you're creating an instance of IDisposable
which is only used withoun the function and not properly calling Dispose
on it. This is due to your use of the FileStream
instance. The proper way to resolve this is to use a using
block
using (FileStream aFile = new FileStream(doFilePath, FileMode.OpenOrCreate)) {
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(templateString, fileNameList, topLevelTestbench);
sw.Close();
}
EDIT
Note: A much easier way to do this is to use File.AppendAllText
.
try
{
var line = String.Format(templateString, fileNameList, topLevelTestbench);
File.AppendAllText(doFilePath, line);
}
catch (IOException e)
{
...
}
精彩评论