如何修复对象'oFs'可以在方法中多次处理

时间:2015-09-13 20:13:14

标签: c# visual-studio code-analysis vs-community-edition

代码

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.

如何解决这个问题?

1 个答案:

答案 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对象是否被正确处理。