代码
public static void StrToFile(string value, string cFileName)
{
if (File.Exists(cFileName) == true)
{
File.Delete(cFileName);
}
FileStream oFs = new FileStream(cFileName, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter oWriter = new StreamWriter(oFs);
oWriter.Write(value);
oWriter.Flush();
oWriter.Close();
oFs.Close();
}
导致Visual Studio Community Edition代码在oFs.Close();
行分析错误Warning CA2202 Object 'oFs' can be disposed more than once in method 'Core.StrToFile(string, string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
如何解决这个问题?
答案 0 :(得分:1)
此处的问题是您将FileStream
对象的所有权授予StreamWriter
对象。因此,当您关闭/处置StreamWriter
对象时,FileStream
对象也会被关闭/处置,并且分析引擎知道这种关系。
尝试使用using
,看看是否有效:
using (FileStream oFs = new FileStream(cFileName, FileMode.CreateNew, FileAccess.ReadWrite))
using (StreamWriter oWriter = new StreamWriter(oFs))
{
oWriter.Write(value);
// oWriter.Flush();
}
如果这不起作用,您可能需要将代码重写为更像这样:
using (var oWriter = new StreamWriter(new FileStream(...)))
{
oWriter.Write(value);
// oWriter.Flush();
}
即。将流传递给作者但后来不存储对它的引用。我个人不喜欢这种变化,因为如果StreamWriter
的构造函数中存在问题,我不确定FileStream
对象是否被正确处理。