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