문제

My encryption code is

{
    AesManaged aes = null;
    MemoryStream memoryStream = null;
    CryptoStream cryptoStream = null;

    try
    {
        Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), 10000);

        aes = new AesManaged();
        aes.Key = rfc2898.GetBytes(32);
        aes.IV = rfc2898.GetBytes(16);

        memoryStream = new MemoryStream();
        cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

        byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
        cryptoStream.Write(data, 0, data.Length);
        cryptoStream.FlushFinalBlock();

        return Convert.ToBase64String(memoryStream.ToArray());
    }
    finally
    {
        if (cryptoStream != null)
            cryptoStream.Close();

        if (memoryStream != null)
            memoryStream.Close();

        if (aes != null)
            aes.Clear();
    }
}

I just tried Code Analysis its giving me

CA2202
Do not dispose objects multiple times 
Object 'memoryStream' can be disposed more than once in method 'EncryptDecrypt.Encrypt(string, string, string)'. 
To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

But my code is working fine I created memoryStream & cryptoStream & closed them after... but I am not able to understand why is it telling me multiple objects multiple times

도움이 되었습니까?

해결책

The guidelines for IDisposable state that disposing the same object twice should have no effect the second time.

However, not all implementations follow this guideline, so Code Analysis tells you not to rely on it.

Your particular objects are safe in this regard, so you don't have an actual problem.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top