This is a literal answer to your question, in that it will not issue CA warnings without suppressing them, and will only ever call every Dispose
once:
MemoryStream encryptedStream = null;
CryptoStream cryptStream = null;
try {
encryptedStream = new MemoryStream();
cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write);
cryptStream.Write(inputInBytes, 0, inputInBytes.Length);
cryptStream.FlushFinalBlock();
result = encryptedStream.ToArray();
} finally {
if (cryptStream != null) {
cryptStream.Dispose();
} else {
if (encryptedStream != null) encryptedStream.Dispose();
}
}
string output = Convert.ToBase64String(result);
But any developer worth their salt should take a look at this and go "hmm, it's like they didn't know using
, I'd better rewrite that". Do not do this in production code. Suppress the warning. Getting code like this correct (and having it remain correct in the face of changes) is actually harder than writing code that uses using
with suppression of spurious warnings (indeed, I'm not entirely sure the above code is correct!). It defeats the entire point of having static code analysis in the first place: to write reliable code. You should see code analysis as a tool, not an arbiter of correctness.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…