如何获取在目录中创建的特定模式的最新文件 [英] How to get the latest file of certain pattern created in a directory

查看:52
本文介绍了如何获取在目录中创建的特定模式的最新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用下面的代码获取最新的内容;但是我想要以特定模式创建的最新版本,而不仅仅是最新创建的

I could get the latest created by using this below; but I want the latest created with certain pattern, not just the latest created

 var directory = new DirectoryInfo("D:\\my_dir\\dir_1\\dir_2\\");
        var smf_log_name = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();

推荐答案

好,

Well, DirectoryInfo.GetFiles has an overload that takes a pattern argument

var directory = new DirectoryInfo("D:\\my_dir\\dir_1\\dir_2");
var smf_log_name = directory.GetFiles("*.txt").OrderByDescending(f => f.LastWriteTime).First();

请注意传递的模式,如果没有指定模式的文件,则序列将抛出InvalidOperationException

Pay attention to the pattern passed, if there are no files with the pattern specified the sequence will throw an InvalidOperationException

FileInfo result = null;
var directory = new DirectoryInfo("D:\\my_dir\\dir_1\\dir_2");
var list = directory.GetFiles("*.txt");
if(list.Count() > 0)
{
    result = list.OrderByDescending(f => f.LastWriteTime).First();
}

这篇关于如何获取在目录中创建的特定模式的最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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