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)
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);
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 +"*";
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.