简体   繁体   中英

Regex Directory.GetFiles Illegal characters in path c#

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 .

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();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM