你基本上需要的是一个安全的,递归的,.exe
根文件夹的搜索功能,你可以将它应用到任何地方。
事情是这样的:
public static List<string> GetAllAccessibleFiles(string path, string searchPattern) {
List<string> dirPathList = new List<string>();
try {
string[] childFilePaths = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
dirPathList.AddRange(childFilePaths);
foreach (string childDirPath in Directory.GetDirectories(path)) { //foreach child directory, do recursive search
List<string> grandChildDirPath = GetAllAccessibleFiles(childDirPath, searchPattern);
if (grandChildDirPath != null && grandChildDirPath.Count > 0) //this child directory has children and nothing has gone wrong
dirPathList.AddRange(grandChildDirPath); //add the grandchildren to the list
}
return dirPathList; //return the whole list found at this level
} catch (UnauthorizedAccessException ex){
//Do something if necessary
return null; //something has gone wrong, return null
}
}
要小心两件事的:
- 并非所有的目录都可以访问。当您尝试访问无法访问的目录时,您将获得
UnauthorizedAccessException
- 通过使用递归搜索,您希望您的搜索结果失败只有在您没有访问权限的目录中。
不过,如果将此应用于所有文件夹,可能需要很长时间。最好将其应用于您要搜索.exe
文件的特定文件夹。
说明:
在功能方面,给出的路径,如果先列出的目录中顶层文件夹中的文件:
string[] childFilePaths = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
dirPathList.AddRange(childFilePaths);
如果你的任何文件的搜索模式匹配,你加这些文件。然后下次检查每个文件夹在你的路径目录包括:
foreach (string childDirPath in Directory.GetDirectories(path)) { //foreach child directory, do recursive search
List<string> grandChildDirPath = GetAllAccessibleFiles(childDirPath, searchPattern);
if (grandChildDirPath != null && grandChildDirPath.Count > 0) //this child directory has children and nothing has gone wrong
dirPathList.AddRange(grandChildDirPath); //add the grandchildren to the list
}
如果任何目录包含的任何子文件夹中,做递归搜索到孩子的目录,并将结果在dirPathList
加在一起,最后返回它:
return dirPathList; //return the whole list found at this level
然后你可以得到所有的文件与".exe"
。
而且在抓,你可能要检查是否有未经授权的访问异常:
catch (UnauthorizedAccessException ex){
//Do something
return null; //something has gone wrong, return null
}
你使用这样的:
List<string> exefiles = YourClassNameWhoHasTheMethod.GetAllAccessibleFiles(testfolder, "*.exe"));
例如,你可以使用回收站测试像这样:
string rbin = @"C:\$Recycle.Bin";
List<string> files = GetAllAccessibleFiles(rbin, "*.exe");
这些是我得到的文件:
C:\$Recycle.Bin\S-1-5-21-3161714743-1342575415-982792061-1001\$IYFMY6V.exe
C:\$Recycle.Bin\S-1-5-21-3161714743-1342575415-982792061-1001\$RYFMY6V.exe
提示:看看'Directory'类:https://msdn.microsoft.com/en-us/library/system.io.directory –
是不是Directory.GetFiles方法(字符串,字符串,SearchOption )? – arn48
那你试过了吗? –