How to delete file after download with ASP.NET MVC?

后端 未结 13 1048
执念已碎
执念已碎 2020-12-07 20:51

I want to delete a file immediately after download, how do I do it? I\'ve tried to subclass FilePathResult and override the WriteFile method where

13条回答
  •  不知归路
    2020-12-07 21:37

    Read in the bytes of the file, delete it, call the base controller's File action.

    public class MyBaseController : Controller
    {
        protected FileContentResult TemporaryFile(string fileName, string contentType, string fileDownloadName)
        {
            var bytes = System.IO.File.ReadAllBytes(fileName);
            System.IO.File.Delete(fileName);
            return File(bytes, contentType, fileDownloadName);
        }
    }
    

    BTW, you may refrain from this method if you're dealing with very large files, and you're concerned about the memory consumption.

提交回复
热议问题