CA2202, how to solve this case

后端 未结 12 970
闹比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:47

    Avoid all usings and use nested Dispose-Calls!

        public static byte[] Encrypt(string data, byte[] key, byte[] iv)
        {
            MemoryStream memoryStream = null;
            DESCryptoServiceProvider cryptograph = null;
            CryptoStream cryptoStream = null;
            StreamWriter streamWriter = null;
    
            try
            {
                memoryStream = new MemoryStream();
                cryptograph = new DESCryptoServiceProvider();
                cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                streamWriter = new StreamWriter(cryptoStream);
    
                streamWriter.Write(data);
                return memoryStream.ToArray();
            }
            finally 
            {
                if(streamWriter != null)
                    streamWriter.Dispose();
                else if(cryptoStream != null)
                    cryptoStream.Dispose();
                else if(memoryStream != null)
                    memoryStream.Dispose();
    
                if (cryptograph != null)
                    cryptograph.Dispose();
            }
        }
    

提交回复
热议问题