To decrease memory usage when returning a file to a client, whilst decrypting, we have gone with streams. This was working fine until one quirk which is that when you upload the same file back to the server (e.g. when a client modifies it). It causes .net core to throw "the process cannot access the file path because it is being used by another process".
As this system is still in development, I'm unsure whether it's a quirk of running the application in debug mode rather than release. Although I built the code into release and still received the same error.
From what I'm aware of how return a stream works, it should dispose the streams automatically.
The first method that creates a stream contains the following:
return (await Decrypt(File.OpenRead(path), AesKey, AesIv), contentType);
The decrypt method then performs the following:
public static async Task<MemoryStream> Decrypt(FileStream data, string key, string iv)
{
Aes aes = Aes.Create();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Padding = PaddingMode.Zeros;
aes.Key = Encoding.ASCII.GetBytes(key);
aes.IV = Encoding.ASCII.GetBytes(iv);
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
return await PerformCryptography(data, decryptor);
}
This then calls the crypto method:
private static async Task<MemoryStream> PerformCryptography(FileStream data, ICryptoTransform cryptoTransform)
{
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write);
await data.CopyToAsync(cryptoStream);
cryptoStream.FlushFinalBlock();
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
This returns back up the chain to the controller that returns the following:
return File(file, contentType, fileName);
When I was developing this, it seemed wrapping any of these in using would cause an object disposed exception, however I may have done something wrong.
Does anyone know how to fix something like this?