Search code examples
c#.netc#-4.0file-iopath-finding

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.

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

Im out of ideas, please help


Solution

  • First, Directory.GetFiles() is wildly inefficient for enumerating file system objects. Directory.EnumerateFileSystemEntries() does the same job in a significantly more optimal way.

    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. 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.