the code below generates a CA2202 in code analysis - do not dispose of objects more than once. Given that I need access to the memory stream after I have called the CryptoStream write method I can't set the ms variable to null until the end of the try block and this causes the CA2202.
Has anyone got any thoughts on how to improve this code to eleminate the error.
public static byte Encrypt(byte clearData, byte key, byte initializationVector)
byte encryptedData = null;
MemoryStream ms = null;
ms = new MemoryStream();
using (Rijndael alg = Rijndael.Create())
alg.Key = key;
alg.IV = initializationVector;
using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
cs.Write(clearData, 0, clearData.Length);
encryptedData = ms.ToArray();
ms = null;
if (ms != null)
View Complete Post