我想列出该目录的目录和子目录中包含的每个文件和目录.如果我选择C:\作为目录,程序将获得它有权访问的硬盘驱动器上的每个文件和文件夹的每个名称.
列表可能看起来像
fd\1.txt fd\2.txt fd\a\ fd\b\ fd\a\1.txt fd\a\2.txt fd\a\a\ fd\a\b\ fd\b\1.txt fd\b\2.txt fd\b\a fd\b\b fd\a\a\1.txt fd\a\a\a\ fd\a\b\1.txt fd\a\b\a fd\b\a\1.txt fd\b\a\a\ fd\b\b\1.txt fd\b\b\a
Directory.GetFiles方法在第一次遇到没有访问权限的文件夹时失败.
该方法抛出一个UnauthorizedAccessException(可以捕获),但到此时,该方法已经失败/终止.
我正在使用的代码如下:
try
{
// looks in stated directory and returns the path of all files found
getFiles = Directory.GetFiles(
@directoryToSearch,
filetype,
SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException)
{
}
Run Code Online (Sandbox Code Playgroud)
据我所知,没有办法事先检查某个文件夹是否具有定义的访问权限.
在我的示例中,我正在通过网络搜索磁盘,当我遇到仅限root访问权限的文件夹时,我的程序失败了.
我正在运行下面的代码并在下面获得例外.我是否被迫将此函数放入try catch中,还是以其他方式递归获取所有目录?我可以编写自己的递归函数来获取文件和目录.但我想知道是否有更好的方法.
// get all files in folder and sub-folders
var d = Directory.GetFiles(@"C:\", "*", SearchOption.AllDirectories);
// get all sub-directories
var dirs = Directory.GetDirectories(@"C:\", "*", SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)
"拒绝访问路径'C:\ Documents and Settings \'."
从VB6时代开始,当我通过系统上的目录递归时,我能够以相对适当的方式使用"on next error next".如果我的"foreach"循环遇到Permission Denied或Access Denied错误,我所要做的就是调用"resume next"语句.
然而,在C#中,这不存在,我理解为什么.然而,令人难以理解的是在C#中弄清楚这是如何实现的.
我试图通过我的硬盘上的目录递归并填充TreeView控件.
private void PopulateTree(string dir, TreeNode node)
{
try
{
// get the information of the directory
DirectoryInfo directory = new DirectoryInfo(dir);
// loop through each subdirectory
foreach (DirectoryInfo d in directory.GetDirectories("*", SearchOption.AllDirectories))
{
// create a new node
TreeNode t = new TreeNode(d.Name);
// populate the new node recursively
PopulateTree(d.FullName, t);
node.Nodes.Add(t); // add the node to the "master" node
}
// lastly, loop through each file in the directory, and …Run Code Online (Sandbox Code Playgroud) 我正在使用此代码搜索所有驱动器中的所有目录以搜索所有.txt文件:
public List<string> Search()
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
}
return files;
}
Run Code Online (Sandbox Code Playgroud)
但在运行中我遇到了这个错误:

怎么解析呢?
谢谢.