Search code examples
c#visual-studiocode-analysisvs-community-edition

How to fix Object 'oFs' can be disposed more than once in method


Code

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();
}

causes in Visual Studio Community Edition code Analyze error at line 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.

How to fix this ?


Solution

  • The issue here is that you give ownership of the FileStream object to the StreamWriter object. Thus, when you close/dispose of the StreamWriter object, the FileStream object is closed/disposed of as well, and the analysis engine knows about this relationship.

    Try using using instead, see if that works:

    using (FileStream oFs = new FileStream(cFileName, FileMode.CreateNew, FileAccess.ReadWrite))
    using (StreamWriter oWriter = new StreamWriter(oFs))
    {
        oWriter.Write(value);
        // oWriter.Flush();
    }
    

    If that doesn't work you may need to rewrite your code to more like this:

    using (var oWriter = new StreamWriter(new FileStream(...)))
    {
        oWriter.Write(value);
        // oWriter.Flush();
    }
    

    ie. pass the stream to the writer but then don't store a reference to it. Personally I don't like this variation since if there is a problem inside the constructor of StreamWriter, I'm not sure the FileStream object is correctly disposed of.