Question

I have some code which looks in a base directory for the most recent file that was written to (modified). The code works fine in that it finds the exact file I am after but if there is a system file, such as 'Thumbs.db' and if that file is the most recent file that was written to, I will find that file (when I don't want to). Is there a way to exclude returning certain file types? The files I am after are all XLS (or XLSX). Here is the code I am using:

var vAmeriDirectory = new DirectoryInfo(ConfigurationManager.AppSettings["AmeriFileSourceLoc"]);
var vAmeriFile = vAmeriDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
Was it helpful?

Solution

Since you know you only want XLS and XLSX files, add a where clause to ensure you only get those extensions:

var vAmeriFile = vAmeriDirectory.GetFiles()
.Where(f => f.Extension.Equals(".xls", StringComparison.InvariantCultureIgnoreCase) 
  || f.Extension.Equals(".xlsx", StringComparison.InvariantCultureIgnoreCase))
.OrderByDescending(f => f.LastWriteTime).First();

Linebreaks added for readability. Note that if there aren't any Excel files in the directory, First() will throw an error. You may want to use FirstOrDefault() instead, which would return null.

OTHER TIPS

You would insert a Where call into your LINQ code to filter the data, using whatever condition will exclude the appropriate files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top