C#中:从目录获取最新的5(最后修订)文件 [英] C#: Get the 5 newest (last modified) files from a directory

查看:561
本文介绍了C#中:从目录获取最新的5(最后修订)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,我可以使用阵列

Is there a way I can store the file location of the 5 last modified files from a directory using Array?

我目前使用下面的下列代码来获得最后一个文件:

I am currently using the following codes below to get the last file:

DateTime lastHigh = new DateTime(1900,1,1);
string highDir;
foreach (string subdir in Directory.GetDirectories(path)){
    DirectoryInfo fi1 = new DirectoryInfo(subdir);
    DateTime created = fi1.LastWriteTime;

    if (created > lastHigh){
        highDir = subdir;
        lastHigh = created;
    }
}



我将使用阵列将多个文件发送到一个电子邮件地址作为附件。

I'll be using Array to send multiple files to an email address as attachment.

更新

我目前使用下面的代码来获得最后修改的文件1分钟后:

I am currently using the codes below to get the last modified files after 1 minute:

string myDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                  "Test Folder");
var directory = new DirectoryInfo(myDirectory);
DateTime from_date = DateTime.Now.AddMinutes(-1);
DateTime to_date = DateTime.Now;
var files = directory.GetFiles().Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);



我要存储从文件来文件名列表

推荐答案

下面是使用LINQ做到这一点的一般方式:

Here's a general way to do this with LINQ:

 Directory.GetFiles(path)
             .Select(x => new FileInfo(x))
             .OrderByDescending(x => x.LastWriteTime)
             .Take(5)
             .ToArray()

我怀疑这是你想要的并不完全,因为你的代码示例似乎在不同的任务是工作,但在一般的情况下,这会做你的问题的请求的标题。

I suspect this isn't quite what you want, since your code examples seem to be working at different tasks, but in the general case, this would do what the title of your question requests.

这篇关于C#中:从目录获取最新的5(最后修订)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆