Find a file that contains multiple words

Hi,

I would like to be able to find the most recently modified file in a directory that contains multiple words in the filename. The words can appear in any order in the file.
I have a line below that almost works. It’s fine for examples like this, (Test_File_Final.xlsx) but if the word Final was at the start of the filename it won’t find it. (Final_Test_File.xlsx)

String.Join(“”, Directory.GetFiles(FileLocationVariable,“* Test * File * Final * .xlsx”,SearchOption.AllDirectories).OrderByDescending(Function(d) New FileInfo(d).Lastwritetime).Take(1) )

Any help here is greatly appreciated.

Hello @dcharlton

the reason its not working on the second scenario is its searching the words in that particular order as mentioned…

why dont you try this code

string.Join("|",Directory.GetFiles(File_Path,"*Final*.xlsx").OrderByDescending(Function(d) New FileInfo(d).Lastwritetime).Take(1) )

this checks for the word final in any position…

2 Likes

Thanks for the help @vickydas.
I also need to check that the filename contains “Test” and “File” as well as “Final”. Where any of those words can appear in any order.
Is there a way to do this?

Hello @dcharlton
try this code

String.Join("|",Directory.GetFiles(File_Path).Select(Function(r) system.Text.RegularExpressions.Regex.Match(CStr(r),"Final.+Test.+File|Test.+File.+Final|File.+Final.+Test").ToString ).OrderByDescending(Function(d) New FileInfo(d).Lastwritetime).take(1) )+".xlsx"

What i have done here is read all the file one by one and match a certain combination(total 3 combination) of your file name.If it matches then it’ll proceed further in our next step and then get the desired result…

Try it and let me know about it

2 Likes

Thanks again @vickydas
It is throwing an error now unfortunately.

The path is not of a legal form.

Any idea why this may be the case?

There are no illegal characters in the path. It is the same path that i was using originally.

Hi @vickydas,

I’ve decided to change up the code to get it to work.
I’ve gotten it to assign all .xls files that contain the word final into an array in descending order.
It will loop through each element of the array and see if contains the other keywords until it finds a match.

Thanks for you help on this.