有什么不对下面code..The给出的代码是不是投诉CA2000:失去范围(https://msdn.microsoft.com/library/ms182289.aspx)之前释放对象。这个代码生成以下警告.NET代码分析警告
警告CA2000在方法CryptoComputer.Encrypt(字符串,字符串,字符串,字符串)',对象'new RijndaelManaged()'不沿着所有的异常路径。调用System.IDisposable.Dispose对象'new RijndaelManaged()'之前,所有对它的引用超出范围。
public static string Encrypt(string plainText, string passPhrase, string saltValue, string initVector)
{
var initVectorBytes = Encoding.UTF8.GetBytes(initVector);
var saltValueBytes = Encoding.UTF8.GetBytes(saltValue);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
string cipherText;
PasswordDeriveBytes password = null;
RijndaelManaged symmetricKey = null;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize/8);
symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherTextBytes = memoryStream.ToArray();
cipherText = Convert.ToBase64String(cipherTextBytes);
}
catch (Exception)
{
throw;
}
finally
{
password?.Dispose();
symmetricKey?.Dispose();
memoryStream?.Dispose();
}
return cipherText;
}
我怎么可以重写这段代码,以满足微软的准则
使用 “使用(......)” 为密码,symmetricKey,MemoryStream的。 –
或者是因为Microsoft的分析规则不能识别“password?.Dispose()”的语法?如果将其重写为'if(obj!= null)obj.Dispose();'? – kennyzx
Kennyzx可能是正确的...您必须以旧方式编写代码或者抑制虚假警告 –