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

后端 未结 13 1049
执念已碎
执念已碎 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:50

    You can return just regular FileStreamResult which is opened with FileOptions.DeleteOnClose. File stream will be disposed with result by asp.net. This answer dosen't require usage of low level response methods which may backfire in certain situations. Also no extra work will be done like loading file to memory as whole.

    var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
    return File(
        fileStream: fs,
        contentType: System.Net.Mime.MediaTypeNames.Application.Octet,
        fileDownloadName: "File.abc");
    

    This answer is based on answer by Alan West and comment by Thariq Nugrohotomo.

提交回复
热议问题