[英]C# Find the newest created *.txt file in specified directory AND sub-directories?
I have now tried everything but something is not working: 我现在已经尝试了所有方法,但是有些方法不起作用:
I need to find the newest Date Created *.txt file in my specified directory and sub-directories. 我需要在指定的目录和子目录中找到最新的创建日期* .txt文件。
string tPath = "C:\MyDirectory";
string[] fDir = Directory.GetFiles(tPath, "*.txt", SearchOption.AllDirectories);
filePath = fDir[0];
Adding, the following leads to and compilation error: 此外,以下导致和编译错误:
string[] fDir = Directory.GetFiles(tPath, "*.txt", SearchOption.AllDirectories).OrderByDescending(f => f.LastWriteTime).First();
Error CS1061 'string' does not contain a definition for 'LastWriteTime' and no extension method 'LastWriteTime' accepting a first argument of type 'string' could be found 错误CS1061'字符串'不包含'LastWriteTime'的定义,并且找不到扩展方法'LastWriteTime'接受类型为'string'的第一个参数
Im out of ideas, please help 我没有想法,请帮忙
First, Directory.GetFiles()
is wildly inefficient for enumerating file system objects. 首先, Directory.GetFiles()
在枚举文件系统对象方面效率低下。 Directory.EnumerateFileSystemEntries()
does the same job in a significantly more optimal way. Directory.EnumerateFileSystemEntries()
以最佳得多的方式完成了相同的工作。
Next, what GetFiles()
(and EnumerateFileSystemEntries()
, for that matter) return is a collection of full paths to file system objects, which is why your second snippet is failing to compile. 接下来, GetFiles()
(和EnumerateFileSystemEntries()
)返回的是文件系统对象的完整路径的集合,这就是第二个代码段无法编译的原因。 Try something like 尝试类似
foreach(var fileInfo in Directory.EnumerateFileSystemEntries().Select(s => new FileInfo(s))
This might fail too (permissions, EnumerateFileSystemEntries()
returning directory paths, etc.), but will get you going. 这也可能会失败(权限, EnumerateFileSystemEntries()
返回目录路径等),但可以助您一臂之力。
Thanks for the help, actually found the answer to my own question: 感谢您的帮助,实际上找到了我自己的问题的答案:
string tPath = "C:\MyDirectory";
filePath = Directory.EnumerateFiles(tPath, "*.txt", SearchOption.AllDirectories).OrderByDescending(File.GetCreationTime).First();
the difference was: OrderByDescending(File.GetCreationTime).First()
区别是: OrderByDescending(File.GetCreationTime).First()
NOT OrderByDescending(f => f.GetCreationTime).First()
NOT OrderByDescending(f => f.GetCreationTime).First()
ps thanks for the tip about .enumeratefiles ps感谢您提供有关.enumeratefiles的提示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.