June 5, 2017

C# - Delete files older than N number of Days/Months in a directory

In this post, I will share C# code to delete files from specific directory, with the condition that only files which are older than N number of Days or Month or any other time unit. Why I come to this code because recently we faced this problem because of not deleting the older files.

I was working on a small utility program to automate repeated tasks, one of which is to take daily backups for my project's database. This was done before, but after some time we faced this problem because we were running out of space, it happens for the reason that we have lot of backup files generated and no one is going to delete older files which are of no-use. The best solution come to my mind is to modify the program code to delete older files by it-self.

Here is the C# code for this task.

string[] files = Directory.GetFiles(directoryPath);

foreach (string file in files)
   FileInfo fi = new FileInfo(file);
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-1))

Obviously you can change DateTime.Now.AddMonths method to AddDays, AddHours or other units according to your requirements.

No comments:

Post a Comment