Directory.GetFiles(LocalFilePath,searchPattern);
MSDN备注:
在searchPattern中使用星号通配符(如".txt“)时,当扩展长度恰好为三个字符时,匹配行为与扩展名长度大于或小于三个字符时的匹配行为不同。文件扩展名为三个字符的searchPattern返回扩展名为三个或更多字符的文件,其中前三个字符与searchPattern中指定的文件扩展名匹配。文件扩展名为1、2或超过3个字符的searchPattern只返回扩展名与searchPattern中指定的文件扩展名完全匹配的文件。使用问号通配符时,此方法只返回与指定文件扩展名匹配的文件。例如,给定目录中的两个文件"file1.txt“和"file1.txtother","file?.txt”的搜索模式只返回第一个文件,而搜索模式"file.txt“则返回两个文件。
下面的列表显示了searchPattern参数的不同长度的行为:
*.abc返回扩展名为.abc、.abcd、.abcde、.abcdef的文件,因此on.*.abcd只返回扩展名为.abcd.*.abcde的文件,只返回扩展名为.abcde.*.abcdef的文件,只返回扩展名为.abcdef的文件。将searchPattern参数设置为*.abc后,如何返回扩展名为.abc (而不是.abcd、.abcde等)的文件?
也许这个功能会起作用:
private bool StriktMatch(string fileExtension, string searchPattern)
{
bool isStriktMatch = false;
string extension = searchPattern.Substring(searchPattern.LastIndexOf('.'));
if (String.IsNullOrEmpty(extension))
{
isStriktMatch = true;
}
else if (extension.IndexOfAny(new char[] { '*', '?' }) != -1)
{
isStriktMatch = true;
}
else if (String.Compare(fileExtension, extension, true) == 0)
{
isStriktMatch = true;
}
else
{
isStriktMatch = false;
}
return isStriktMatch;
}测试计划:
class Program
{
static void Main(string[] args)
{
string[] fileNames = Directory.GetFiles("C:\\document", "*.abc");
ArrayList al = new ArrayList();
for (int i = 0; i < fileNames.Length; i++)
{
FileInfo file = new FileInfo(fileNames[i]);
if (StriktMatch(file.Extension, "*.abc"))
{
al.Add(fileNames[i]);
}
}
fileNames = (String[])al.ToArray(typeof(String));
foreach (string s in fileNames)
{
Console.WriteLine(s);
}
Console.Read();
}还有其他更好的解决方案吗?
发布于 2009-01-13 04:05:00
不是一个错误,是不正常的,而是有据可查的行为。*.doc基于8.3回退查找与*.docx匹配。
您必须手动对结果进行后置过滤,以便在doc中结束。
发布于 2009-01-13 07:06:07
使用linq..。
string strSomePath = "c:\\SomeFolder";
string strSomePattern = "*.abc";
string[] filez = Directory.GetFiles(strSomePath, strSomePattern);
var filtrd = from f in filez
where f.EndsWith( strSomePattern )
select f;
foreach (string strSomeFileName in filtrd)
{
Console.WriteLine( strSomeFileName );
}发布于 2009-01-13 10:08:11
这在短期内不会有帮助,但就这一问题在岗位上的投票可能会在未来发生变化。
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95415
https://stackoverflow.com/questions/437914
复制相似问题