CA2202, how to solve this case

后端 未结 12 956
闹比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:52

    When a StreamWriter is disposed, it will automatically dispose the wrapped Stream (here: the CryptoStream). CryptoStream also automatically disposes the wrapped Stream (here: the MemoryStream).

    So your MemoryStream is disposed both by the CryptoStream and the using statement. And your CryptoStream is disposed by the StreamWriter and the outer using statement.


    After some experimentation, it seems to be impossible to get rid of warnings completely. Theorectically, the MemoryStream needs to be disposed, but then you theoretically couldn't access its ToArray method anymore. Practically, a MemoryStream does not need to be disposed, so I'd go with this solution and suppress the CA2000 warning.

    var memoryStream = new MemoryStream();
    
    using (var cryptograph = new DESCryptoServiceProvider())
    using (var writer = new StreamWriter(new CryptoStream(memoryStream, ...)))
    {
        writer.Write(data);
    }
    
    return memoryStream.ToArray();
    

提交回复
热议问题