Search code examples
c#fileinfo

Get most recent file with a certain prefix


I am trying to get the most recent file from a directory that also has a certain prefix. I am able to successfully use the code if I don't put the search string overload in after getfiles(), but if I do use it, I get an exception stating:

An unhandled exception of type 'System.InvalidOperationException' has occurred in System.Core.dll

FileInfo mostrecentlog = (from f in logDirectory.GetFiles("Receive") orderby f.LastWriteTime descending select f).First();

Solution

  • Well, you need to ask few questions to yourself.

    What if there is no matching file? Will your current implementation work? no. it will crash. Why? because of .First() operator.

    As you mentioned, you want to find files with certain prefix, so add wildcard * to your prefix. Find all files starting with some prefix.

    FileInfo mostrecentlog = (from f in logDirectory.GetFiles("your_pattern*") orderby
                                          f.LastWriteTime descending select f).FirstOrDefault();
    

    Now check if mostrecentlog is not null, if it's not null then it will contain your most recent file matching certain prefix.