CA2202, how to solve this case

后端 未结 12 1110
闹比i
闹比i 2020-11-22 08:18

Can anybody tell me how to remove all CA2202 warnings from the following code?

public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
    us         


        
12条回答
  •  迷失自我
    2020-11-22 08:40

    I wanted to solve this the right way - that is without suppressing the warnings and rightly disposing all disposable objects.

    I pulled out 2 of the 3 streams as fields and disposed them in the Dispose() method of my class. Yes, implementing the IDisposable interface might not necessarily be what you are looking for but the solution looks pretty clean as compared to dispose() calls from all random places in the code.

    public class SomeEncryption : IDisposable
        {
            private MemoryStream memoryStream;
    
            private CryptoStream cryptoStream;
    
            public static byte[] Encrypt(string data, byte[] key, byte[] iv)
            {
                 // Do something
                 this.memoryStream = new MemoryStream();
                 this.cryptoStream = new CryptoStream(this.memoryStream, encryptor, CryptoStreamMode.Write);
                 using (var streamWriter = new StreamWriter(this.cryptoStream))
                 {
                     streamWriter.Write(plaintext);
                 }
                return memoryStream.ToArray();
            }
    
           public void Dispose()
            { 
                 this.Dispose(true);
                 GC.SuppressFinalize(this);
            }
    
           protected virtual void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (this.memoryStream != null)
                    {
                        this.memoryStream.Dispose();
                    }
    
                    if (this.cryptoStream != null)
                    {
                        this.cryptoStream.Dispose();
                    }
                }
            }
       }
    

提交回复
热议问题