Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net DirectoryInfo wild card pattern to handle exclusion

Tags:

c#

The following method call returns all xml files in the given directory.

FileInfo[] Files = Directory.GetFiles("*.xml");

I would like to get all XML files in the directory where the fileName does not end with "_update.xml"

for example.... if I have the following files

ABC.xml
ABC2.xml
ABC3_update.xml

then I want a call that will only return:

ABC.xml
ABC2.xml

Is this possible?

like image 799
JL. Avatar asked Jan 13 '10 19:01

JL.


2 Answers

I don't believe you can use search wildcards for that kind of exclusion. You can, however, filter the list of files after the fact. It's quite easy with LINQ. Although, if your directory is very large, this may result in a lot of processing of the file list in memory.

Try:

FileInfo[] files = 
    Directory.GetFiles("*.xml")  // all XML files
         .Where( fi => !fi.Name.EndsWith( "_update.xml", CurrentCultureIgnoreCase ) )
         .ToArray();
like image 99
LBushkin Avatar answered Sep 30 '22 01:09

LBushkin


Not with a wildcard mapping like this, no. You'll need to remove the ones you don't want afterwards.

Note that Directory.GetFiles("*.xml") is actually interpreted as matching all files with extensions beginning with xml, not just equal to xml - a quirk of the method! So you may have to exclude other files as well in a similar way.

On this page of MSDN it's explained like this:

When using the asterisk wildcard character in a searchPattern (for example, ".txt"), the matching behavior varies depending on the length of the specified file extension. A searchPattern with a file extension of exactly three characters returns files with an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern. A searchPattern with a file extension of one, two, or more than three characters returns only files with extensions of exactly that length that match the file extension specified in the searchPattern. When using the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files in a directory, "file1.txt" and "file1.txtother", a search pattern of "file?.txt" returns only the first file, while a search pattern of "file.txt" returns both files.

like image 32
David M Avatar answered Sep 30 '22 01:09

David M