我想知道 Directory.GetFiles 方法的搜索模式逻辑是什么。我在搜索模式中使用星号通配符。如果我将“*”放在字符前面,我不明白在搜索时应用什么样的逻辑。
如果我把“*”放在字符前面,我会得到意想不到的结果,但如果我把“*”放在字符后面,结果是正确的。
这是文件夹中的文件列表、示例代码和结果。
字符前面有星号
string _strSearchPattern = "*1";
foreach (string _strFolder in Directory.GetFiles(@"C:\Temp\FileList", _strSearchPattern))
Console.WriteLine("{0}", _strFolder);
意想不到的结果。应该是 1.为什么出来了“b_Request”但为什么没有包含“b”?
字符后面的星号
string _strSearchPattern = "1*";
foreach (string _strFolder in Directory.GetFiles(@"C:\Temp\FileList", _strSearchPattern))
Console.WriteLine("{0}", _strFolder);
这是预期结果
是bug还是我想太多了?
最佳答案
这有点棘手,但不是错误。
星号 (*) 代表该位置中的零个或多个字符,问号 (?) 代表该位置中的零个或一个字符。
根据MSDN :
Because this method checks against file names with both the 8.3 file name format and the long file name format, a search pattern similar to "*1*.txt" may return unexpected file names. For example, using a search pattern of "*1*.txt" returns "longfilename.txt" because the equivalent 8.3 file name format is "LONGFI~1.TXT".
在第一种情况下,带有“*1”的搜索路径将匹配任何以字母 1 结尾的路径,将返回路径 1 和路径 b_Request(使用 8.3 文件名格式 b_Requ~1)。
您可以引用here有关 8.3 文件名的更多信息。
关于c# - Directory.GetFiles 方法上的 searchPattern 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062076/