This question may seem to you duplicate of CA2202, how to solve this case which has an accepted answer. But you may realize that accepted answer has 5 down votes based on poor quality. Also any other up voted answers are not actually solves the issue. Most of them explains how to suppress the rule or debates about how wrong this rule is and why we should ignore it. Since that rule is there, there should be a way to satisfy it and I'm looking for community support to solve that issue.
I'm trying to figure it out how to satisfy CA2202 in the following code. I understand that the issue here is, using statement also disposes the encryptedStream object. But if I remove the finally part, it starts to throw CA2000
So, what is the correct way of writing it to comply with CA2202 and CA2000
byte[] result;
MemoryStream encryptedStream = null;
try
{
encryptedStream = new MemoryStream();
using (var cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptStream.Write(inputInBytes, 0, inputInBytes.Length);
cryptStream.FlushFinalBlock();
result = encryptedStream.ToArray();
}
}
finally
{
encryptedStream?.Dispose();
}
string output = Convert.ToBase64String(result);