Last Updated: February 25, 2016
· tellez12

Deleting temp files older than 2 hours with c#

We have a folder in our applications with some temp files uploaded by the users, if they complete the process this files get moved to some other folders, but if the users don't finish it, we are stuck with some useless and untracked files.

My first thought was to create a scheduled task but managing this is hard and without documenting it (or even with it) could be forgotten really easy, so instead whenever I save a file to the temp folder I would delete all files that are older than 2 hours.
Let me know what do you think of this approach, here is a snippet of my code:

string dirPath = ConfigurationManager.AppSettings["pathVideosTemp"];
        foreach (string file in Directory.GetFiles(dirPath))            {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddHours(-2))