我正在尝试使用ActionFilter删除在我的控制器上动态生成的文件。
public class DeleteFileAttribute : ActionFilterAttribute {
public override void OnActionExecuted(ActionExecutedContext context) {
/* MVC 4 code which worked just fine
context.HttpContext.Response.Flush();
var filePathResult = context.Result as FilePathResult;
if(filePathResult!=null){
File.Delete(filePathResult.FileName);
}
End of MVC 4 code */
// I am not able to flush response as context.HttpContext.Response does not have a Flush method
var vb = (context.Controller as Controller).ViewBag;
string fileToDelete = vb.FileToDelete;
if(File.Exists(fileToDelete)) {
// ERROR: Process cannot access the file ... because it is being used by another process
File.Delete(fileToDelete);
}
}
}
正如代码注释中所提到的,由于我无法刷新响应然后删除文件,我得到IOException: The process cannot access the file ... because it is being used by another process
例外。
在用户完成下载后,在操作过滤器中删除文件的确切方法是什么?
答案 0 :(得分:0)
在操作过滤器中使用OnResultExecuted
事件代替OnActionExecuted
解决了该问题。不需要刷新响应。