C#:从目录中获取 5 个最新(上次修改)的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11388141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:41:46  来源:igfitidea点击:

C#: Get the 5 newest (last modified) files from a directory

c#linqfiledirectory

提问by abramlimpin

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

有没有办法可以使用 存储目录中最后修改的 5 个文件的文件位置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 Arrayto send multiple files to an email address as attachment.

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

UPDATE

更新

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

我目前正在使用以下代码在 1 分钟后获取最后修改的文件:

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);

I want to store to list of file names coming from files

我想存储到来自的文件名列表 files

采纳答案by Paul Phillips

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

这是使用 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 generalcase, this would do what the title of your question requests.

我怀疑这不是您想要的,因为您的代码示例似乎正在处理不同的任务,但在一般情况下,这将满足您的问题标题的要求。

回答by Matt Mitchell

It sounds like you want a stringarray of the full filepaths of all the files in a directory.

听起来您想要一个string目录中所有文件的完整文件路径数组。

Given you already have your FileInfoenumerable, you can do this:

鉴于您已经有了FileInfo可枚举,您可以这样做:

var filenames = files.Select(f => f.FullName).ToArray();

If you wanted just the filenames, replace FullNamewith Name.

如果您只想要文件名,请替换FullNameName.