Delete files older than 2 months old in a directory in C#
To delete file older than 2 months in C# we need to loop through all files by getting files list usingDirectory.GetFiles()
and check LastAccessTime
from FileInfo
if it's before Now -2 months.Example
using System.IO;
using System;
public class Example
{
public static void Main()
{
string dirName = @"C:\Folder_Path";
string[] files = Directory.GetFiles(dirName);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.LastAccessTime < DateTime.Now.AddMonths(-2))
fi.Delete();
}
}
}