C#实现目录内关键词任意位置匹配的文件/目录搜索问题
SearchManager Class Hey David, I see exactly what's going on here—your current code is only matching items that start with the user's input because of the way you're constructing the search pattern: user_input + "*" tells GetDirectories and GetFiles to look for names that begin with the input string followed by anything else.
To make the search find items where the input appears anywhere in the name, you just need to wrap the user's input with wildcard characters (*) on both sides. Here's how to adjust your code:
Modified Code
public class SearchManager { //Returns a list of items that contain the user's input within a given path public static List<string> SearchResults(string current_path, string user_input) { DirectoryInfo dir_info = new DirectoryInfo(current_path); // Wrap user_input with * to match any position in the name string searchPattern = $"*{user_input}*"; DirectoryInfo[] directories = dir_info.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly); FileInfo[] files = dir_info.GetFiles(searchPattern, SearchOption.TopDirectoryOnly); List<string> ItemsFound = new List<string>(); foreach (DirectoryInfo dir in directories) ItemsFound.Add(dir.FullName); foreach (FileInfo file in files) ItemsFound.Add(file.FullName); return ItemsFound; } }
What Changed?
- We created a
searchPatternvariable that uses$"*{user_input}*"—this wildcard pattern means "any sequence of characters, followed by the user's input, followed by any sequence of characters". - We replaced both instances of
user_input + "*"with this new pattern, so both directories and files will be matched if their names contain the input string anywhere.
Bonus: Case-Insensitive Search (Optional)
If you want the search to ignore uppercase/lowercase differences (e.g., "txt" matches "TextFile.txt"), you can use EnumerationOptions instead of the basic SearchOption to enable case insensitivity:
var searchOptions = new EnumerationOptions { IgnoreCase = true, SearchDepth = 1 // Equivalent to SearchOption.TopDirectoryOnly }; DirectoryInfo[] directories = dir_info.GetDirectories(searchPattern, searchOptions); FileInfo[] files = dir_info.GetFiles(searchPattern, searchOptions);
This makes the search more user-friendly, especially if your users might type in lowercase but the files/directories use uppercase.
内容的提问来源于stack exchange,提问作者David G

