Scott Chamberlain Scott Chamberlain - 8 days ago 6
C# Question

Can a CryptoStream be returned and still have everything dispose correctly?

If I have a

CryptoStream
that I want to pass back to the user, the naïve approach would be

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 CryptoStream(fsCrypt, transform, CryptoStreamMode.Read);

return cs;
}


I know that when I dispose the
CryptoStream
the underlying
FileStream
will also be disposed. The issue I am running in to is what do I do with
rmCrypto
and
transform
?
RijndaelManaged
and
ICryptoTransform
are disposable classes, but disposing of the stream does not dispose those two objects.

What is the correct way to handle this situation?

Ian Ian
Answer

I'd consider creating your own class that wraps the stream and then you can manage the disposal of these. Somethings along these lines (sorry - don't know the type of the transform object off top of my head).

public CryptoStreamWrapper : Stream, IDisposable
{
    public CryptoStreamWrapper(CryptoStream stream, RijndaelManaged rmCrypto, IDisposable transform)
    {
        this.transform = transform;
        this.rmCrypto = rmCrypto;
        this.stream = stream;
    }

    public void Dispose()
    {
        this.transform.Dispose();
        this.rmCrypto.Dispose();
        this.stream.Dispose();
    }
}