Frage

I'm working on search function for my self-made Windows Explorer. I use Directory.GetFiles(string path, string searchPattern, searchOption searchOption) to do that. My problem is that when I call:

string searchPattern = '"' + searchBox.Text + '"'; // searchPattern = "duck"
string path = @"D:\test";
string[] searchResults = Directory.GetFiles(path, searchPattern, System.IO.SearchOption.AllDirectories);

It throws the exception:

"Illegal characters in path."

This is the file structure:

D:\
---test\ (Folder)
-------duck.txt (File)
War es hilfreich?

Lösung

Directory.GetFiles does not support regular expressions. It does, however, support a handful of special 'wildcard' characters. From MSDN:

* Zero or more characters.
? Exactly zero or one character.

Try this instead:

string searchPattern = '*' + searchBox.Text + '*'; // searchPattern = *duck*
string path = @"D:\test";
string[] searchResults = Directory.GetFiles(path, searchPattern, System.IO.SearchOption.AllDirectories);

Andere Tipps

You get "Illegal characters in path.". because you have given " characters in your search pattern

try with

string searchPattern ="duck.txt"; 

you will find the file you want

if you need to give only the file name as search pattern then

string searchPattern =searchBox.Text +".txt"; 

if you need to get files contain your search text you can use

string searchPattern ="*" +searchBox.Text +"*"; 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top