Andrew Truckle
Andrew Truckle

Reputation: 19117

CA2202 Code Anaysis issue with Dispose

I can't get my head around the resolution to these code analysis warnings.

This is the code:

   public static string Crypt(string s_Data, string s_Password, bool b_Encrypt)
    {
        byte[] u8_Salt = new byte[] { ... };

        PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(s_Password, u8_Salt);

        Rijndael i_Alg = Rijndael.Create();
        i_Alg.Key = i_Pass.GetBytes(32);
        i_Alg.IV = i_Pass.GetBytes(16);

        ICryptoTransform i_Trans = (b_Encrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

        MemoryStream i_Mem = new MemoryStream();
        CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

        byte[] u8_Data;
        if (b_Encrypt)
            u8_Data = Encoding.Unicode.GetBytes(s_Data);
        else
            u8_Data = Convert.FromBase64String(s_Data);

        try
        {
            i_Crypt.Write(u8_Data, 0, u8_Data.Length);
            i_Crypt.Close();
            if (b_Encrypt)
                return Convert.ToBase64String(i_Mem.ToArray());
            else
                return Encoding.Unicode.GetString(i_Mem.ToArray());
        }
        catch
        {
            return null;
        }
        finally
        {
            i_Crypt.Close();
        }
    }

The errors are being raised on the i_Crypt.Close(); call. I can see that I have that call twice in my code.

Errors:

Errors

Upvotes: 0

Views: 88

Answers (1)

Derrick Moeller
Derrick Moeller

Reputation: 4950

Simply remove the Close(); from your try block.

try
{
    i_Crypt.Write(u8_Data, 0, u8_Data.Length);
    if (b_Encrypt)
        return Convert.ToBase64String(i_Mem.ToArray());
    else
        return Encoding.Unicode.GetString(i_Mem.ToArray());
}
catch
{
    return null;
}
finally
{
    i_Crypt.Close();
}

Even better, if you tried a little bit you could likely use your MemoryStream and the CryptoStream in a using block.

Should I call Close() or Dispose() for stream objects?

Using block vs IDisposabe.Dispose()

Upvotes: 3

Related Questions