johnnie
johnnie

Reputation: 2057

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?

Upvotes: 4

Views: 4320

Answers (2)

Jerry Nixon
Jerry Nixon

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

Jeff Mercado
Jeff Mercado

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

Related Questions