I don't see any issue about using the multiple using
statements to dispose the objects.
It's common to have nested using statements and your code is valid.
Using objects of different types, you can nest using the one-line syntax if you want to save space and improve readability:
using (MemoryStream msDecrypt = new MemoryStream(encryptedText.ToBase64Byte()))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
The issue you encountered is recurrent using the Code Analysis (you can find the cause of the warning here). You can then ignore the warning about the multiple using statements, because this is a false positive and your code is fine and valid.
You can also suppress the warning in this way (thanks to @Jordão), as described in this nice answer:
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public void MyMethodWithUsings()
{
using (MemoryStream msDecrypt = new MemoryStream(encryptedText.ToBase64Byte()))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
If you want to remove the warning, you'll have to rewrite your code using the block try/finally
and call the Dispose()
method of your objects in the finally
block, but this will produce awful and not easy to read code, as you can see in this question.