Moien Tajik Moien Tajik - 4 months ago 37
ASP.NET (C#) Question

revoke and delete file after specific time asp.net mvc

I upload a file in my website and make download link for user with a guid + file extension and copy that new file in another folder.

I want to revoke download link and delete that new file after 10 minutes , or is that true to revoke link after one time request?

How i can do this ?

Answer

To delete the file you either need to write a Windows Service to poll the files, or if you want to keep it really basic you can check for old files every time the page loads.

Here's the basic version:

When a user requests a download, check the creation date of all files in the target directory. If a file is over 10 minutes old - delete it. After clearing up the files it's then a simple check to see if the target file the user has requested still exists or not

You can check the creation date and delete files using the following:

        string[] files = System.IO.Directory.GetFiles(@"C:\_Temp", "*.txt");
        foreach (string file in files) {
            DateTime creation = System.IO.File.GetCreationTime(file);
            if (((TimeSpan)(DateTime.Now - creation)).TotalMinutes > 10) {
                System.IO.File.Delete(file);
            }
        }

NOTE: Make sure you don't have any important files in the target directory. Change "*.txt" to match the file format of your uploaded files.

Next, check if the requested file still exists using:

if (File.Exists(@"C:\test.txt")) { 
    // process file here
}

Hope that helps :)