0

Below code triggers exception:

string[] filenames=Directory.GetFiles( "path from config",
"*MAIN.txt|*CONT.txt", SearchOption.TopDirectoryOnly).ToArray()

I want to pull all files into a array from a directory containing MAIN.txt or CONT.txt in the file name.
But when i run the code it is giving me System.ArgumentException, Illegal characters in path exception.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
T. Mara
  • 11
  • 1
  • Welcome to SO! The second parameter is not a regular expression. It is a "search string" that can only accept * and ? characters. – Ryan H. Sep 28 '18 at 21:56
  • Possible duplicate of [Can you call Directory.GetFiles() with multiple filters?](https://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters) – Lance U. Matthews Sep 29 '18 at 06:18

2 Answers2

2

To elaborate further, the reason you are getting the ArgumentException is because the second parameter is not valid.

The overload of the Directory.GetFiles method that you are using is expecting a string path, string searchPattern, and a SearchOption searchOption.

The searchPattern is not a regular expression. You can only use a combination of * and ? characters.

From the documentation:

The search string to match against the names of files in path. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.

Alternative implementation using the System.Linq Concat extension method:

string[] mainFileNames = Directory.GetFiles(@"/Some/Path", "*MAIN.txt", SearchOption.TopDirectoryOnly);
string[] contFileNames = Directory.GetFiles(@"/Some/Path", "*CONT.txt", SearchOption.TopDirectoryOnly);

string[] allFileNames = mainFileNames.Concat(contFileNames).ToArray();
Ryan H.
  • 2,543
  • 1
  • 15
  • 24
1

Those aren't regular expressions. Anyway, Directory.GetFiles doesn't support filename expressions with the | character. You'll need to call that method twice, and then combine the arrays together.

string[] mainNames=Directory.GetFiles("path from config","*MAIN.txt",SearchOption.TopDirectoryOnly);
string[] contNames=Directory.GetFiles("path from config","*CONT.txt",SearchOption.TopDirectoryOnly);

string[] fileNames= new string[mainNames.Length + contNames.Length];
Array.Copy(mainNames, fileNames, mainNames.Length);
Array.Copy(contNames, 0, fileNames, mainNames.Length, contNames.Length);
Ruzihm
  • 19,749
  • 5
  • 36
  • 48