我收到警告:
Severity Code Description Project File Line Suppression State
Warning CA2000 Call System.IDisposable.Dispose on object created by 'new RNGCryptoServiceProvider()' before all references to it are out of scope. JobsLedger.AUTHORISATION C:\Users\simon\OneDrive\Documents\1.0 - AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedger.AUTHORISATION\CryptoService.cs 96 Active
此警告发生的代码在此行上:
new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);
它的用法如下:
public string EncryptdatabaseName(string text)
{
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);
using var aesAlg = Aes.Create();
using var encryptor = aesAlg.CreateEncryptor(salt, aesAlg.IV);
using var msEncrypt = new MemoryStream();
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var encryptedDatabaseName = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, encryptedDatabaseName, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, encryptedDatabaseName, iv.Length, decryptedContent.Length);
// Format hash with extra information
return string.Format(CultureInfo.CurrentCulture, "$DATABASENAME$V1${0}${1}", Convert.ToBase64String(encryptedDatabaseName), salt);
}
我正在使用Visual Studio 2019及其正在抛出该错误的Roslyn编译器。我想摆脱警告。
我该如何处置?
答案 0 :(得分:2)
CA2000的意思是“在失去作用域之前处置对象”。在official document中,您可以尝试以下代码:
using(RNGCryptoServiceProvider test = new RNGCryptoServiceProvider())
{
test.GetBytes(salt = new byte[SaltSize]);
}
如果您想直接隐藏它,可以使用以下代码,就像:
#pragma warning disable CA1062
new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);
#pragma warning restore CA1062