小编典典

CA2202,如何解决这种情况

c#

谁能告诉我如何从以下代码中删除所有CA2202警告?

public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
    using(MemoryStream memoryStream = new MemoryStream())
    {
        using (DESCryptoServiceProvider cryptograph = new DESCryptoServiceProvider())
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                using(StreamWriter streamWriter = new StreamWriter(cryptoStream))
                {
                    streamWriter.Write(data);
                }
            }
        }
        return memoryStream.ToArray();
    }
}

警告7
CA2202:Microsoft。用法:对象’cryptoStream’可以在方法’CryptoServices.Encrypt(string,byte
[],byte
[])’中多次处置。为避免生成System.ObjectDisposedException,不应在一个对象上调用Dispose多次。:行:34

警告8
CA2202:Microsoft。用法:对象’memoryStream’可以在方法’CryptoServices.Encrypt(string,byte
[],byte
[])’中多次处置。为了避免生成System.ObjectDisposedException,不应在一个对象上调用Dispose多次。:行:34,37

您需要Visual Studio代码分析才能查看这些警告(这些不是c#编译器警告)。


阅读 286

收藏
2020-05-19

共1个答案

小编典典

编译时没有警告:

    public static byte[] Encrypt(string data, byte[] key, byte[] iv)
    {
        MemoryStream memoryStream = null;
        DESCryptoServiceProvider cryptograph = null;
        CryptoStream cryptoStream = null;
        StreamWriter streamWriter = null;
        try
        {
            memoryStream = new MemoryStream();
            cryptograph = new DESCryptoServiceProvider();
            cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write);
            var result = memoryStream;              
            memoryStream = null;
            streamWriter = new StreamWriter(cryptoStream);
            cryptoStream = null;
            streamWriter.Write(data);
            return result.ToArray();
        }
        finally
        {
            if (memoryStream != null)
                memoryStream.Dispose();
            if (cryptograph != null)
                cryptograph.Dispose();
            if (cryptoStream != null)
                cryptoStream.Dispose();
            if (streamWriter != null)
                streamWriter.Dispose();
        }
    }

*根据评论进行 *编辑
:我再次验证了此代码不会生成警告,而原始代码会生成警告。在原始代码中,CryptoStream.Dispose()MemoryStream().Dispose(实际上被调用了两次(可能有问题也可能没有问题)。

修改后的代码的工作方式如下:null将处置责任转移到另一个对象后,将引用设置为。例如memoryStreamnull在对CryptoStream构造函数的调用成功之后,将其设置为。成功调用构造函数后,将cryptoStream设置为。如果没有异常,则将其放置在块中,然后依次将和放置。null``StreamWriter``streamWriter``finally``CryptoStream``MemoryStream

2020-05-19