Don_B Don_B - 3 months ago 11
Vb.net Question

Finding txt files inside a given folder with subfolders?

Can anyone tell me how can I find say *.txt files inside a given folder inside which there are subfolders in the structure 12345\30123\128\txt\100.txt, the main folder can contain other subfolders or txt files but I only want to get the txt files which reside in the subfolders of the format 12345\30123\128\txt\100.txt. i.e. txt files inside all txt folders

I have tried this:

Dim txtFilesArray As String() = Directory.GetFiles(targetDirectory, "*.txt", SearchOption.AllDirectories)


But it gets all txt files?

Answer
Dim txtFiles = Directory.EnumerateFiles(targetDirectory,"*.txt",SearchOption.AllDirectories)
          .Where(Function(f) f Like "*\#*\#*\#*\txt\#*.txt")

where # matches any digit from 0 to 9 and * matches any 0 or more characters

or slower RegEx version will be something like

Dim txtFiles = Directory.EnumerateFiles(targetDirectory,"*.txt",SearchOption.AllDirectories)
          .Where(Function(f) RegEx.IsMatch(f, ".*\\\d+\\\d+\\\d+\\txt\\\\d+\.txt"))

For Each txtFile In txtFiles 
    '...
Next