The Microsoft docs have the following piece of code on this page:
The most inner 'using' statement suppose to Dispose csEncrypt, which in it's turn suppose to Dispose the msEncrypt stream. However, right after the most inner using statement scope the msEncrypt is still alive and is used (the ToArray() of it is called).
The Microsoft document clearly states: "The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.". The latter means that the csEncrypt is also disposed/closed, which in its turn closes the msEncrypt (https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/cryptostream.cs,23052627697efb77, Can a CryptoStream leave the base Stream open?).
Then please explain how we can still call the "msEncrypt.ToArray();" after the end of scope of the innermost using statement?
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}