CA2202, how to solve this case

后端 未结 12 1111
闹比i
闹比i 2020-11-22 08:18

Can anybody tell me how to remove all CA2202 warnings from the following code?

public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
    us         


        
12条回答
  •  迷失自我
    2020-11-22 08:43

    I was faced with similar issues in my code.

    Looks like the whole CA2202 thing is triggered because MemoryStream can be disposed if exception occurs in constructor (CA2000).

    This could be resolved like this:

     1 public static byte[] Encrypt(string data, byte[] key, byte[] iv)
     2 {
     3    MemoryStream memoryStream = GetMemoryStream();
     4    using (DESCryptoServiceProvider cryptograph = new DESCryptoServiceProvider())
     5    {
     6        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write);
     7        using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
     8        {
     9            streamWriter.Write(data);
    10            return memoryStream.ToArray();
    11        }
    12    }
    13 }
    14
    15 /// 
    16 /// Gets the memory stream.
    17 /// 
    18 /// A new memory stream
    19 private static MemoryStream GetMemoryStream()
    20 {
    21     MemoryStream stream;
    22     MemoryStream tempStream = null;
    23     try
    24     {
    25         tempStream = new MemoryStream();
    26
    27         stream = tempStream;
    28         tempStream = null;
    29     }
    30     finally
    31     {
    32         if (tempStream != null)
    33             tempStream.Dispose();
    34     }
    35     return stream;
    36 }
    

    Notice that we have to return the memoryStream inside the last using statement (line 10) because cryptoStream gets disposed at line 11 (because it's used in streamWriter using statement), which leads memoryStream to get also disposed at line 11 (because memoryStream is used to create the cryptoStream).

    At least this code worked for me.

    EDIT:

    Funny as it may sound, I discovered that if you replace the GetMemoryStream method with the following code,

    /// 
    /// Gets a memory stream.
    /// 
    /// A new memory stream
    private static MemoryStream GetMemoryStream()
    {
        return new MemoryStream();
    }
    

    you get the same result.

提交回复
热议问题