如何修复对象 'oFs' 可以在方法中多次处理
How to fix Object 'oFs' can be disposed more than once in method
代码
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 社区版代码分析第 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.
如何解决这个问题?
这里的问题是您将 FileStream
对象的所有权授予了 StreamWriter
对象。因此,当您 StreamWriter
对象的 close/dispose 时, FileStream
对象也是 closed/disposed 的,并且分析引擎知道这种关系。
尝试使用 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
对象是否被正确处理。
代码
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 社区版代码分析第 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.
如何解决这个问题?
这里的问题是您将 FileStream
对象的所有权授予了 StreamWriter
对象。因此,当您 StreamWriter
对象的 close/dispose 时, FileStream
对象也是 closed/disposed 的,并且分析引擎知道这种关系。
尝试使用 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
对象是否被正确处理。