Search code examples
c#getfilesdirectoryinfo

GetFiles exclude a string


with the following code I am able to get all files that includes a string in their name:

DirectoryInfo dirInf = new DirectoryInfo(path);
FileInfo[] fInfArray = dirInf.GetFiles("*string*");

But how do I exclude a string at GetFiles.
I dont mean the ending like .txt I want to exclude a string in the name of the file.

For example I have the following files:

wordwordfile.msg  
wordwordfile.txt  
wodfile.txt

and exclude wod to get the following files:

wordwordfile.msg  
wordwordfile.txt  

Solution

  • var files = new DirectoryInfo("C:\\")
                    .EnumerateFiles("*string*")
                    .Where(f => !f.Name.Contains("wod"))
                    // Optional, convert to array if you want
                    .ToArray();