我创建了一个MemoryStream,将它传递给CryptoStream进行写入。我想让CryptoStream加密,并让MemoryStream打开,让我读入其他内容。但是一旦处理完CryptoStream,它也会处理掉MemoryStream。
CryptoStream能以某种方式让基本MemoryStream保持打开状态吗?
using (MemoryStream scratch = new MemoryStream())
{
using (AesManaged aes = new AesManaged())
{
// <snip>
// Set some aes parameters, including Key, IV, etc.
// </snip>
ICryptoTransform encryptor = aes.CreateEncryptor();
using (CryptoStream myCryptoStream = new CryptoStream(scratch, encryptor, CryptoStreamMode.Write))
{
myCryptoStream.Write(someByteArray, 0, someByteArray.Length);
}
}
// Here, I'm still within the MemoryStream block, so I expect
// MemoryStream to still be usable.
scratch.Position = 0; // Throws ObjectDisposedException
byte[] scratchBytes = new byte[scratch.Length];
scratch.Read(scratchBytes,0,scratchBytes.Length);
return Convert.ToBase64String(scratchBytes);
}发布于 2013-11-02 06:54:07
您可以,但不能使用using语句。您将需要手动管理对象的处置,还需要调用FlushFinialBlock()以确保在对其进行操作之前所有数据都已写出到底层流中。
一旦您完成了对流的处理,您就可以在最后的finally块中处理您等待的所有资源。
MemoryStream scratch = null;
AesManaged aes = null;
CryptoStream myCryptoStream = null;
try
{
scratch = new MemoryStream();
aes = new AesManaged();
// <snip>
// Set some aes parameters, including Key, IV, etc.
// </snip>
ICryptoTransform encryptor = aes.CreateEncryptor();
myCryptoStream = new CryptoStream(scratch, encryptor, CryptoStreamMode.Write);
myCryptoStream.Write(someByteArray, 0, someByteArray.Length);
//Flush the data out so it is fully written to the underlying stream.
myCryptoStream.FlushFinalBlock();
scratch.Position = 0;
byte[] scratchBytes = new byte[scratch.Length];
scratch.Read(scratchBytes,0,scratchBytes.Length);
return Convert.ToBase64String(scratchBytes);
}
finally
{
//Dispose all of the disposeable objects we created in reverse order.
if(myCryptoStream != null)
myCryptoStream.Dispose();
if(aes != null)
aes.Dispose();
if(scratch != null)
scratch.Dispose();
}发布于 2018-06-15 23:41:50
从.NET 4.7.2开始,有了第二个构造函数,它添加了一个名为leaveOpen的布尔参数。如果设置为true,则CryptoStream的dispose方法将不会调用基础流上的dispose。
Additionally,另一个不带leaveOpen参数的构造函数只是将参数转发给leaveOpen设置为false的新构造函数。
发布于 2013-11-02 23:39:41
作为第二种解决方案,您可以创建一个WrapperStream对象,该对象简单地传递除Dispose / Close之外的所有调用。在内存流周围做一个包装器,将包装器递给加密流,现在关闭加密流并不会接触到内存流。
https://stackoverflow.com/questions/19736631
复制相似问题