skaz
skaz

Reputation: 22580

Delete Temporary File with FileStreamResult

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"));
    }
}

Upvotes: 6

Views: 3021

Answers (2)

Jacob
Jacob

Reputation: 78850

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):

public ActionResult Download()
{
    using (var stream = new MemoryStream())
    {
        CreateFile(this.DataContext, stream);
        stream.Position = 0; // Not sure if this is necessary
        return File(stream, MimeTypeUtil.GetMimeType("xlsx"), "MyFile.xlsx");
    }
}

FileStreamResult is sort of a misnomer. It appears to accept any Stream object, not just file streams.

Upvotes: 1

archil
archil

Reputation: 39501

Seems like exact fit for creating custom ResultFilter. You could directly subclass ActionFilterAttribute. Something along these lines (missing part of file name detection)

public class ResultFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        string fileName = //((FileStreamResult)filterContext.Result). ???

        File.Delete(fileName);
    }
}

You could create custom ActionResult by subclassing FileStreamResult to pass along temp file name. Then the deletion would be trivial.

Upvotes: 5

Related Questions