你基本上需要的是一個安全的,遞歸的,.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
那你試過了嗎? –