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 )
  {
    filterContext.HttpContext.Response.Flush();
    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: ,
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s