最重要的规则在搜索可能包含的文件夹时难以接近的子文件夹是:
Do NOT use SearchOption.AllDirectories
!
Use SearchOption.TopDirectoryOnly
相反,结合递归搜索对于所有可访问的目录。
Using SearchOption.AllDirectories
, one即使在处理任何文件/目录之前,访问冲突也会破坏整个循环。但如果你使用SearchOption.TopDirectoryOnly
,您只会跳过无法访问的内容。
还有更难使用的方法Directory.GetAccessControl()
每个子目录检查您是否可以事先访问目录(尽管这个选项相当困难 - 我真的不推荐这样做,除非您确切地知道访问系统是如何工作的)。
对于递归搜索,我实现了以下代码供我自己使用:
public static List<string> GetAllAccessibleDirectories(string path, string searchPattern) {
List<string> dirPathList = new List<string>();
try {
List<string> childDirPathList = Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly).ToList(); //use TopDirectoryOnly
if (childDirPathList == null || childDirPathList.Count <= 0) //this directory has no child
return null;
foreach (string childDirPath in childDirPathList) { //foreach child directory, do recursive search
dirPathList.Add(childDirPath); //add the path
List<string> grandChildDirPath = GetAllAccessibleDirectories(childDirPath, searchPattern);
if (grandChildDirPath != null && grandChildDirPath.Count > 0) //this child directory has children and nothing has gone wrong
dirPathList.AddRange(grandChildDirPath.ToArray()); //add the grandchildren to the list
}
return dirPathList; //return the whole list found at this level
} catch {
return null; //something has gone wrong, return null
}
}
这就是你所说的
List<string> accessibleDirs = GetAllAccessibleDirectories(myrootpath, "*");
然后,您只需在所有文件中搜索/添加文件即可无障碍目录。
注:这个问题很古典尽管。我相信还有其他一些更好的解决方案。
如果在获取所有可访问目录后,您特别想要避免某些目录,您还可以过滤这些目录List
LINQ 使用目录名称的一部分作为关键字(即Recycle.Bins
).