Reputation: 2057
I am trying to write a method that gets files from a folder, orders it by creation time, takes the top five latest files and deletes the rest.
Any help will be much appreciated, my code that i have is as follows:
DirectoryInfo Dir = new DirectoryInfo(DirectoryPath);
FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
var x = FileList.OrderByDescending(file => file .CreationTime).Take(5);
How do I amend this code to delete all the other files?
Upvotes: 4
Views: 4320
Reputation: 31813
Here's what I did:
var directory = new DirectoryInfo(DirectoryPath);
var query = directory.GetFiles("*.bmp", SearchOption.AllDirectories);
foreach (var file in query.OrderByDescending(file => file.CreationTime).Skip(1))
{
file.Delete();
}
Upvotes: 4
Reputation: 134881
As you are keeping the first N
and doing something else with the rest, it would be better to just loop through everything, throwing the first N
into a separate list while calling Delete()
on the rest.
var query = fileList.OrderByDescending(file => file.CreationTime);
var keepers = new List<FileInfo>();
var i = 0;
foreach (var file in query)
{
if (i++ < N)
{
keepers.Add(file);
}
else
{
file.Delete();
}
}
Upvotes: 4