-1

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 ?

Andrus
  • 26,339
  • 60
  • 204
  • 378
  • 1
    Discussion [here](http://stackoverflow.com/questions/3831676/ca2202-how-to-solve-this-case) may help you. – Blorgbeard Sep 13 '15 at 20:16
  • I though permission to use search before asking question is unlocked at 3475 points :) - while your case may be different it is not yet clear in which way top search result for ca2202 did not help you. Please update your post to clarify. – Alexei Levenkov Sep 13 '15 at 20:19

1 Answers1

1

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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Nested usings has the same issue. Have a look here: https://msdn.microsoft.com/en-us/library/ms182334.aspx where this exact example is described! – fabspro Jan 03 '16 at 00:02