伊恩打我的基本概念(go upvote him),但CryptoStream的本身是不密封的,因此是微不足道的做一個派生類包裝了需要處理的事情。
/// <summary>
/// Creates a class that creates a <see cref="CryptoStream"/> and wraps the disposing action of all the associated objects
/// </summary>
class ReturnableCryptoStream : CryptoStream
{
private readonly ICryptoTransform _transform;
private readonly IDisposable _algorithm;
public ReturnableCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
: this(stream, transform, mode, null)
{
}
public ReturnableCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, IDisposable algorithm)
: base(stream, transform, mode)
{
_transform = transform;
_algorithm = algorithm;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (_transform != null)
_transform.Dispose();
if (_algorithm != null)
_algorithm.Dispose();
}
}
}
一樣使用
public Stream GetDecryptedFileStream(string inputFile, byte[] key, byte[] iv)
{
var fsCrypt = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
var rmCrypto = new RijndaelManaged();
var transform = rmCrypto.CreateDecryptor(key, iv);
var cs = new ReturnableCryptoStream(fsCrypt, transform, CryptoStreamMode.Read, rmCrypto);
return cs;
}
按照你的方法,你''從返回GetDecryptedFileStream'之後,因爲它們在你的方法的局部變量rmCrypto'和'transform'應配置。 –
@YuvalItzchakov走出範圍並不意味着被處置。在最後一次發佈'cs'的引用之前,GC不會完成這兩個對象。 –
哦,我沒有看到你的CryptoStream接受它們作爲參數。 –