Search code examples
c#searchdirectoryfileinfo

How to search a directory for files that begin with something then get the one that was modified most recently


What I want to do is search/scan a directory for multiple files beginning with something, then get the file that was last modified most recently. For example, I want to search the directory Prefetch for files that begin with "apple", "pear", and "orange". These files may not exist, but if they do, and say there are files that begin with apple and files that begin with pear, out of all of those files, I want to get the one that was modified most recently. The code below allows me do to this but search only 1 thing.

DirectoryInfo prefetch = new DirectoryInfo("c:\\Windows\\Prefetch");
FileInfo[] apple = prefetch.GetFiles("apple*");
if (apple.Length == 0)
   // Do something
else
{
   double lastused = DateTime.Now.Subtract(
                     apple.OrderByDescending(x => x.LastWriteTime)
                          .FirstOrDefault().LastWriteTime).TotalMinutes;
   int final = Convert.ToInt32(lastused);
}

Basically, how can I make that code search 'apple', 'pear' etc. instead of just apple? I don't know if you can modify the code above to do that or if you have to change it completely. I've been trying to figure this out for hours and can't do it.


Solution

  • As explained in my comments you can't use DirectoryInfo.GetFiles to return list of FileInfo with so different patterns. Just one pattern is supported.

    As others as already shown, you can prepare a list of patterns and then call in a loop the GetFiles on each pattern.

    However, I would show you the same approach, but done with just one line of code in Linq.

    List<string> patterns = new List<string> { "apple*", "pear*", "orange*" };
    DirectoryInfo prefetch = new DirectoryInfo(@"c:\Windows\Prefetch");  
    
    var result = patterns.SelectMany(x => prefetch.GetFiles(x))
                         .OrderByDescending(k => k.LastWriteTime)
                         .FirstOrDefault();
    

    Now, result is a FileInfo with the most recent update. Of course, if no files matches the three patterns, then result will be null. A check before using that variable is mandatory.