I have used memory stream to download the file. As soon as file get downloaded I need to clear up all memory being used by that memory stream. 

```
context.Response.BufferOutput = true;
//DecryptAndStoreInMemory decrypt a requested file and store in memory
using (MemoryStream ms = DecryptAndStoreInMemory(context.Server.MapPath(path), userFileName))
    {
      byte[] bytesInStream = ms.ToArray();
      context.Response.ContentType = "application/octet-stream";
      context.Response.AddHeader("Content-Length", bytesInStream.Length.ToString());
      context.Response.AddHeader("Content-Disposition", "attachment; filename=" + userFileName);
      ClearStream(ms);
      context.Response.BinaryWrite(bytesInStream);
      context.Response.Flush();
      context.Response.Close();
      Array.Clear(bytesInStream, 0, bytesInStream.Length);
    }

ClearStream(MemoryStream stream)
{
    if(stream != null)
    {
        stream.Flush();
        stream.Close();
        stream.Dispose();
    }
}

```

//Decrypt a file and store in memory stream.

```
public MemoryStream DecryptAndStoreInMemory(string inputFilePath, string userFileName)
{
    MemoryStream msOutput = null;
    if (File.Exists(inputFilePath))
    {
        try
        {
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_password, _salt);
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
                {
                    using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (msOutput = new MemoryStream())
                        {
                            int data;
                            while ((data = cs.ReadByte()) != -1)
                            {
                                msOutput.WriteByte((byte)data);
                            }
                        }
                    }
                }
            }
            return msOutput;
        }
        catch (CryptographicException)
        {
            throw new Exception("Sorry we can not serve " + userFileName + " file at this time.");
        }
        catch (Exception)
        {
            throw;
        }
    }
    else
    {
        throw new Exception("Sorry we could not locate " + userFileName);
    }

}

```

After file is sent to response it doesn't free up the memory being taken. It almost took twice the size of file. 17 MB file takes almost 40 MB memory.

What should be done to free up those space.
I tried to clear byte array but found that it only replaces each element of array with 0 keeps its length same.