Search code examples
c#code-analysisdispose

Why do I get a "Do not dispose objects multiple times" warning on a single using clause?


I have the following code (as an example):

using(Stream s = new FileStream(path))
using(GZipStream gz = new GZipStream(s, CompressionMode.Compress))
{
    //do stuff here
}

I am getting a CA2202 "Do not dispose objects multiple times" error here. Is this simply because I don't use the leaveOpen parameter in my GZipStream?

I have gotten similar errors elsewhere with a single using statement, but apparently multiple calls to Dispose().

Is it the same problem as this question, or something else?


Solution

  • Because the GZipStream also disposes of the Stream. The fix is either to use the leaveOpen parameter on the constructor (which doesn't make much sense in this case since you really want it closed anyway) or combine the statements:

    using(var gz = new GZipStream(new FileStream(path), CompressionMode.Compress))
    {
        // Do Stuff Here
    }