I am using MVC3 to return a temporary file that is created in code. Then, I use FileStreamResult to stream this file back to the client. However, as this is a temporary file that I no longer need, I would like to clean up the file. I don’t know how to do this since I am already hitting the return statement while streaming. Thanks.
public FileStreamResult Download()
{
string filename = Path.GetTempFileName();
using (FileStream stream = new FileStream(filename, FileMode.OpenOrCreate))
{
CreateFile(this.DataContext, stream);
}
using (FileStream outputStream = new FileStream(filename, FileMode.Open))
{
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xlsx");
return new FileStreamResult(outputStream,MimeTypeUtil.GetMimeType("xlsx"));
}
}
You may not actually need a temporary file if your code is like what you posted. (This assumes your method is inside of a
Controller):FileStreamResultis sort of a misnomer. It appears to accept anyStreamobject, not just file streams.