获取最新的N个文件并删除其余文件 [英] Get most recent N files and delete the rest
本文介绍了获取最新的N个文件并删除其余文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一种方法,该方法从文件夹获取文件,按创建时间对其进行排序,获取最新的前五个文件,然后删除其余的文件.
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?
推荐答案
当您保留第一个N
并与其余的做其他事情时,最好遍历所有内容,并抛出第一个N
进入另一个列表,同时调用其余的Delete()
.
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();
}
}
这篇关于获取最新的N个文件并删除其余文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文