Daily Archives: November 5, 2012

Deleting a result file in ASP.NET MVC

It happens sometimes, that you send back a file to the browser from ASP.NET MVC using FilePathResult with some code like this:

public FileResult GetFile()
    // TODO: something important is done here...
    return this.File( filePath, type );

If the file is actually a temporary file, how can you delete the unnecessary file from the server only after the file is fully sent to the browser?

You can create a result filter:

public class DeleteFileAttribute : ActionFilterAttribute
  public override void OnResultExecuted( ResultExecutedContext filterContext )
    string filePath = ( filterContext.Result as FilePathResult ).FileName;
    File.Delete( filePath );

Of course this code is simplified, you should add additional checks to validate that the action result is really a FilePathResult, check that the file exists, and finally make sure that your code doesn’t blow up if the file deletion fails.

After you completed your filter, just add the [DeleteFile] attribute to your action and you’re done!


Technorati-címkék: ,