I had posted something similar to this before, but it was about dealing with the Command Prompt. As in the other instance, I'm trying to do some automated file cleanup prior to a backup in an ERP system I perform maintenance on in order to smooth out the process (as I perform maintenance on at half dozen of these systems at least twice each month). So, here are some examples of what's happening...
Here are three files names that could show up in the directory:
- AP_AnalysisWrk.M4T
- AP_AnalysisWrkMPM201408211313.M4T
- AP_AnalysisWrkNG201408211313.M4T
Of these three, the second two would be candidates for deletion, and the first would need to remain. So, initially I used the following to retrieve only the second two:
String[] wrkFileList = Directory.GetFiles(directoryPath, "??_*Wrk??*????????????.M4T");
However, for some reason, it always returns all three even though the first doesn't match the pattern. When using this pattern in Windows Explorer, it only returns the second two files, as is desired. I have developed a workaround using regular expressions, which works:
Regex wrkFileMatch = new Regex("([A-z]{2}_[A-z0-9]+Wrk[A-Z0-9]{2,3}\\d{12}.(m4t|M4T))$");
I'm not crazy about this approach, though, because it adds a loop which shouldn't be necessary because I have to loop through all results to get the correct results. Performance-wise, it doesn't seem to matter that much, but I'd like to understand why the initial pattern match fails to only return the correct matches. Is there a better method for file name filtering with GetFiles, or am I just better off with iterating through the directory results and using RegEx matches to find the correct files (like I am currently doing)?