Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6827633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:17:18+00:00 2026-05-26T22:17:18+00:00

I have the following code public static byte[] Compress(byte[] CompressMe) { using (MemoryStream ms

  • 0

I have the following code

public static byte[] Compress(byte[] CompressMe)
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress,true))
        {
            gz.Write(CompressMe, 0, CompressMe.Length);
            ms.Position = 0;
            byte[] Result = new byte[ms.Length];
            ms.Read(Result, 0, (int)ms.Length);
            return Result;
        }
    }
}

This works fine, but when I run code analysis on it, it comes up with the following message

CA2202 : Microsoft.Usage : Object 'ms' can be disposed more than once in 
method 'Compression.Compress(byte[])'. To avoid generating a 
System.ObjectDisposedException you should not call Dispose more than one 
time on an object.

As far as I’m concerned, when the GZipStream is Disposed, it leaves the underlying Stream (ms) open, due to the last parameter of the constructor (leaveOpen=true).

If I change my code slightly.. remove the ‘using’ block around the MemoryStream and change the ‘leaveOpen’ parameter to false..

public static byte[] Compress(byte[] CompressMe)
{
    MemoryStream ms = new MemoryStream();
    using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress, false))
    {
        gz.Write(CompressMe, 0, CompressMe.Length);
        ms.Position = 0;
        byte[] Result = new byte[ms.Length];
        ms.Read(Result, 0, (int)ms.Length);
        return Result;
    }
}

This then comes up with..

CA2000 : Microsoft.Reliability : In method 'Compression.Compress(byte[])',
object 'ms' is not disposed along all exception paths. Call 
System.IDisposable.Dispose on object 'ms' before all references to 
it are out of scope.

I can’t win.. (unless I’m missing something obvious) I’ve tried various things, like putting a try/finally around the block, and Disposing of the MemoryStream in there, but it either says that I’m disposing of it twice, or not at all !!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T22:17:19+00:00Added an answer on May 26, 2026 at 10:17 pm

    That is sometimes the problem with running CodeAnalysis, you sometimes you simply cannot win and you have to choose the lesser evil™.

    In this situation, I believe the correct implementation is the second example. Why? According to .NET Reflector, the implementation of GZipStream.Dispose() will dispose of the the MemoryStream for you as GZipStream owns the MemoryStream.

    Relevant parts of GZipStream class below:

    public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
    {
        this.deflateStream = new DeflateStream(stream, mode, leaveOpen, true);
    }
    
    protected override void Dispose(bool disposing)
    {
        try
        {
            if (disposing && (this.deflateStream != null))
            {
                this.deflateStream.Close();
            }
            this.deflateStream = null;
        }
        finally
        {
            base.Dispose(disposing);
        }
    }
    

    As you wouldn’t want to disable the rule entirely, you can suppress for this method only using using the CodeAnalysis.SupressMessage attribute.

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability ", "CA2000:?", Justification = "MemoryStream will be disposed by the GZipStream.")]
    

    Note: You will have fill in the full rule name (i.e. CA2000:?) as I did not know what it was from the error message you posted.

    HTH,

    EDIT:

    @CodeInChaos:

    Looking deeper at the implementation DeflateStream.Dispose I believe it still will dispose of the MemoryStream for you regardless of the leaveOpen option as it calls the base.Dispose().

    EDIT Ignore the above about DeflateStream.Dispose. I was looking at the wrong implementation in Reflector. See comments for details.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following Java code: public static BufferedImage createImage(byte[] data, int width, int
I have the following code to serialize /deserialize a DataTable: public static byte[] Serialize(DataTable
I have been using the following code to Compress data in .Net 4.0: public
I have following code: public static void ProcessStep(Action action) { //do something here if
I have following code public class TEST { public static void main(String arg[]){ try
I have the following code: public static T ParameterFetchValue<T>(string parameterKey) { Parameter result =
i have the following code: public static void Serialize() { List<string> dirs = FileHelper.GetFilesRecursive(fileDirectoryPath);
I have the following code: public class Test { public static void Main() {
Let's assume I have the following code: public class MainClass { public static void
I have the following code: public class Foo {} static class Program { [XmlElement(foo)]

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.