我知道我能做到
Directory.GetFiles(@"c:\", "*.html")然后我将获得一个与*.html文件模式匹配的文件列表。
我想做相反的事情。给定文件名abc.html,我希望有一个方法可以告诉我该文件名是否与*.html模式匹配。例如
class.method("abc.html", "*.html") // returns true
class.method("abc.xml", "*.html") // returns false
class.method("abc.doc", "*.?oc") // returns true
class.method("Jan24.txt", "Jan*.txt") // returns true
class.method("Dec24.txt", "Jan*.txt") // returns false该功能必须存在于dotnet中。我只是不知道它是在哪里暴露的。
将模式转换为正则表达式可能是一种方法。然而,它似乎只是有很多边缘情况,可能会有更多的麻烦比它的价值。
注意:问题中的文件名可能还不存在,所以我不能只包装一个Directory.GetFiles调用,然后检查结果集是否有任何条目。
发布于 2013-03-27 04:39:51
我不认为GetFiles的searchPattern支持完整的正则表达式。下面的代码可以是另一种选择(但性能不是很好)
bool IsMatch(string fileName,string searchPattern)
{
try
{
var di = Directory.CreateDirectory("_TEST_");
string fullName = Path.Combine(di.FullName, fileName);
using (File.Create(fullName)) ;
bool isMatch = di.GetFiles(searchPattern).Any();
File.Delete(fullName);
return isMatch;
}
catch
{
return false;
}
}https://stackoverflow.com/questions/15646555
复制相似问题