Directory.GetFiles(LocalFilePath,searchPattern);
MSDN备注:
在searchPattern中使用星号通配符时,例如".txt",当扩展名正好是三个字符长时的匹配行为与扩展名多于或少于三个字符长时的匹配行为不同.具有三个字符的文件扩展名的searchPattern返回扩展名为三个或更多字符的文件,前三个字符与searchPattern中指定的文件扩展名匹配.文件扩展名为一,二或三个以上字符的searchPattern仅返回扩展名与searchPattern中指定的文件扩展名完全匹配的文件.使用问号通配符时,此方法仅返回与指定文件扩展名匹配的文件.例如,在目录中给定两个文件"file1.txt"和"file1.txtother",搜索模式为"file? .文本"只返回第一个文件,而搜索模式为"file.txt"返回两个文件.
以下列表显示了searchPattern参数的不同长度的行为:
*.abc返回具有扩展名的文件.abc,.abcd,.abcde,.abcdef,等.
*.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;
}
Run Code Online (Sandbox Code Playgroud)
测试程序:
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();
}
Run Code Online (Sandbox Code Playgroud)
别人有更好的解决方案吗?
答案是您必须进行后期过滤.单靠GetFiles 无法做到这一点.这是一个将处理结果的示例.有了这个,您可以使用GetFiles的搜索模式 - 它将以任何方式工作.
List<string> fileNames = new List<string>();
// populate all filenames here with a Directory.GetFiles or whatever
string srcDir = "from"; // set this
string destDir = "to"; // set this too
// this filters the names in the list to just those that end with ".doc"
foreach (var f in fileNames.All(f => f.ToLower().EndsWith(".doc")))
{
try
{
File.Copy(Path.Combine(srcDir, f), Path.Combine(destDir, f));
}
catch { ... }
}
Run Code Online (Sandbox Code Playgroud)