ASP .NET Core
MVC Controller - download file from server storage using FileStream and returning FileStreamResult
public IActionResult Download(string path, string fileName)
{
var fileStream = System.IO.File.OpenRead(path);
return File(fileStream, "application/force-download", fileName);
}
Everything works fine, but once the user cancels downloading before the download is complete, other actions in the controller working with this file (Delete file, rename file) do not work because: The process cannot access the file, because it is being used by another process
FileStream automatically dispose when the file download is complete, but for some reason it does not terminate when the user terminates the download manually.
I have to restart the web application => the program that uses the file is IISExpress
Does anyone please know how to dispose stream if the user manually ends the download?
EDIT:
FileStream stream = null;
try
{
using (stream = System.IO.File.OpenRead(path))
{
return File(stream, "application/force-download", fileName);
}
}
Code that I tried to end the Stream after returning FileStreamResult, I am aware that it can not work, because after return File (stream, contentType, fileName)
it immediately jumps to the block finally and the stream closes, so the download does not start because the stream is closed