johnnie johnnie - 2 months ago 10x
C# Question

Get most recent N files and delete the rest

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?


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)