我试图以这种方式从文件夹中获取所有文件:
try
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException)
{
throw;
}
如果我的根文件夹包含用户无权访问的文件夹,则会捕获UnauthorizedAccessException
并且我的数组为空并且所有递归都失败。
我如何处理此案例并确保我的代码在未经许可的情况下忽略位置但是从具有权限的位置添加文件?
答案 0 :(得分:3)
您可以使用FileSystemInfo对象和递归来完成此任务:
static List<string> files = new List<string>();
static void MyMethod() {
DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
ProcessFolder(dir.GetFileSystemInfos());
}
static void ProcessFolder(IEnumerable<FileSystemInfo> fsi) {
foreach (FileSystemInfo info in fsi) {
// We skip reparse points
if ((info.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
Debug.WriteLine("Skipping reparse point '{0}'", info.FullName);
return;
}
if ((info.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
// If our FileSystemInfo object is a directory, we call this method again on the
// new directory.
try {
DirectoryInfo dirInfo = (DirectoryInfo)info;
ProcessFolder(dirInfo.GetFileSystemInfos());
}
catch (Exception ex) {
// Skipping any errors
// Really, we should catch each type of Exception -
// this will catch -any- exception that occurs,
// which may not be the behavior we want.
Debug.WriteLine("{0}", ex.Message);
break;
}
} else {
// If our FileSystemInfo object isn't a directory, we cast it as a FileInfo object,
// make sure it's not null, and add it to the list.
var file = info as FileInfo;
if (file != null) {
files.Add(file.FullName);
}
}
}
}
MyMethod
获取您选择的路径并使用它创建DirectoryInfo
对象,然后调用GetFileSystemInfos()
方法并将其传递给ProcessFolder
方法。
ProcessFolder
方法查看每个FileSystemInfo
对象,跳过reparse points,如果FileSystemInfo
对象是目录,则再次调用ProcessFolder
方法 - 否则,它将FileSystemInfo
对象强制转换为FileInfo
对象,确保它不为空,然后将文件名添加到列表中。
更多阅读: