-1

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)
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
sonlexqt
  • 6,011
  • 5
  • 42
  • 58
  • I've edited your post. Please read [Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the answer is **no**. – p.s.w.g Oct 16 '13 at 06:59

2 Answers2

4

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);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • One more question: When I use Directory.GetFiles() or Directory.GetDirectories(), I got the UnauthorizedAccessException and the search process stopped (searchResults return null). How can get rid of that ? – sonlexqt Oct 16 '13 at 03:48
  • @Dante_BMW When you use `SearchOption.AllDirectories`, if you do not have permission to access any subdirectory, it will throw that exception. The only way around this (i.e. to handle the exception on directories where you don't have permissions, but still return files in directories where you do have permissions) is to use a recursive function. There are a number of questions on SO about that very topic. – p.s.w.g Oct 16 '13 at 03:52
  • thanks, I'm trying the recursive approach now. My code is here: http://pastebin.com/S8AT6N37. Dont' know why some time there is 2 items display in my listview for the same file ? Wish you can correct it ... thanks so much bro ! – sonlexqt Oct 16 '13 at 04:53
  • @Dante_BMW I don't see anything that stands out, but that really should be a different question. – p.s.w.g Oct 16 '13 at 05:09
0

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 +"*"; 
Damith
  • 62,401
  • 13
  • 102
  • 153