Regular expression for parsing file name and partial path, conditionally

I have a C # application that uses search functions to find all files in a directory and then displays them in a list. I need to be able to filter files based on the extension (possibly using the search function) and the directory (for example, block the display of any "test" or "debug" directories in the directories).

My current code looks something like this:

Regex filter = new Regex(@"^docs\(?!debug\)(?'display'.*)\.(txt|rtf)"); String[] filelist = Directory.GetFiles("docs\\", "*", SearchOption.AllDirectories); foreach ( String file in filelist ) { Match m = filter.Match(file); if ( m.Success ) { listControl.Items.Add(m.Groups["display"]); } } 

(which is somewhat simplified and consolidated, the actual regular expression is created from a string read from a file, and I do more error checking between them.)

I need to select the section (usually the relative path and file name) that will be used as the display name, while ignoring any files with a specific folder name as the section of their path. For example, for those files, only those that have + s should match:

 + docs\info.txt - docs\data.dat - docs\debug\info.txt + docs\world\info.txt + docs\world\pictures.rtf - docs\world\debug\symbols.rtf 

My regular expression works for most of them, except that I'm not sure how to make it unsuccessful in the last file. Any suggestions on how to make this work?

+4
source share
2 answers
 ^docs\\(?:(?!\bdebug\\).)*\.(?:txt|rtf)$ 

will match the line that

  • starts with docs\ ,
  • does not contain debug\ anywhere (binding \b ensures that we match debug as a whole word) and
  • ends with .txt or .rtf .
+2
source

Try Directory.GetFiles . This should do what you want.

Example:

 // Only get files that end in ".txt" string[] dirs = Directory.GetFiles(@"c:\", "*.txt", SearchOption.AllDirectories); Console.WriteLine("The number of files ending with .txt is {0}.", dirs.Length); foreach (string dir in dirs) { Console.WriteLine(dir); } 
+3
source

All Articles