CA2202:对象可以被处置多次

CA2202: Object can be disposed of more than once

我在以下代码片段中收到以下警告,但我不明白为什么

warning CA2202: Microsoft.Usage : Object 'memStream' can be disposed more than once in method 'Encrypt(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

代码:

string Encrypt(string toEncrypt)
{
    byte[] key = ...
    byte[] iv = ...

    using (AesCng aes = new AesCng())
    using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
    using (MemoryStream memStream = new MemoryStream())
    using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
    {
        UTF7Encoding encoder = new UTF7Encoding();
        byte[] bytes = encoder.GetBytes(toEncrypt);

        cryptoStream.Write(bytes, 0, bytes.Length);
        cryptoStream.FlushFinalBlock();

        return Convert.ToBase64String(memStream.ToArray());
    }
}

据我所知,CryptoStream 对象在处理 Stream 时不会处理传入的对象。那么变量memStream怎么可能不止一次被处理掉呢?

非常感谢。

默认情况下,

CryptoStream.Dispose() 将处理基础流。如果你不想要这种行为,你需要使用构造函数 overload,它在 CryptoStream 被释放时显式地使底层流保持打开状态。

您可以看到它是如何实现的 here

您可以使用带 leaveOpen 参数的重载 CryptoStream 构造函数。

并且不需要这个,因为 CryptoStream 对象在使用块

cryptoStream.FlushFinalBlock();

代码:

string Encrypt(string toEncrypt)
{
    byte[] key = ...
    byte[] iv = ...

    using (AesCng aes = new AesCng())
    using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
    using (MemoryStream memStream = new MemoryStream())
    using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write,true))
    {
        UTF7Encoding encoder = new UTF7Encoding();
        byte[] bytes = encoder.GetBytes(toEncrypt);

        cryptoStream.Write(bytes, 0, bytes.Length);

        return Convert.ToBase64String(memStream.ToArray());
    }
}

leaveOpen: true to not close the underlying stream when the CryptoStream object is disposed

CryptoStream ctor