Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 I delete file after

HttpResponseBase.TransmitFile

is called, but this hangs the application.

Can I safely delete a file after user downloads it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...