I have a C# application in which there is a requirement to delete all the files whose date created will be older than today’s date. How can we achieve this?
I had a search in google to find out a sample code. So I decide to create one and post it here.If you want to delete older files from a directory , you can use below method. If you have any queries on this please let me know as well, I am very happy to help you.
public void FolderDelete()
{
DirectoryInfo d = new DirectoryInfo(ConfigurationManager.AppSettings["<path>"]);
if (d.Exists)
{
//Get all Directories from the path
string[] folders = Directory.GetDirectories(d.ToString());
foreach (var item in folders)
{
DirectoryInfo info = new DirectoryInfo(item);
//It will purge the 14 days older directories
if (info.CreationTime < DateTime.Now.AddDays(-14))
{
info.Delete(true);
}
}
}
else
{
Console.WriteLine("There is no 14 days older files.");
}
}
This is very useful and simple to use.I have tried the above method.Could any one of you have another idea, Please share with me.