获取文件递归:跳过无法读取的文件/目录? [英] Getting files recursively: skip files/directories that cannot be read?
本文介绍了获取文件递归:跳过无法读取的文件/目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得的所有目录中的文件的一个数组(包括子文件夹中的文件)
I want to get all of the files in a directory in an array (including the files in subfolders)
string[] filePaths = Directory.GetFiles(@"c:\",SearchOption.AllDirectories);
这里的问题是:如果抛出一个异常,整个命令停止。有没有更好的办法做到这一点,这样,如果一个文件夹不能访问它只是跳过了吗?
The problem with this is: If an exception is thrown the entire command stops. Is there a better way to do this so that if a folder cannot be accessed it will just skip over it?
推荐答案
您可能不得不多做一点打字自己,那么,写一个目录漫步者像这样的:
You'd probably have to do a bit more typing yourself then, and write a directory walker like this one:
public static string[] FindAllFiles(string rootDir) {
var pathsToSearch = new Queue<string>();
var foundFiles = new List<string>();
pathsToSearch.Enqueue(rootDir);
while (pathsToSearch.Count > 0) {
var dir = pathsToSearch.Dequeue();
try {
var files = Directory.GetFiles(dir);
foreach (var file in Directory.GetFiles(dir)) {
foundFiles.Add(file);
}
foreach (var subDir in Directory.GetDirectories(dir)) {
pathsToSearch.Enqueue(subDir);
}
} catch (Exception /* TODO: catch correct exception */) {
// Swallow. Gulp!
}
}
return foundFiles.ToArray();
}
这篇关于获取文件递归:跳过无法读取的文件/目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文