从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 add these as nodes
foreach (FileInfo f in directory.GetFiles())
{
// create a new node
TreeNode t = new TreeNode(f.Name);
// add it to the "master"
node.Nodes.Add(t);
}
}
catch (System.Exception e)
{
MessageBox.Show(e.Message, "Error Loading Directories", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
Run Code Online (Sandbox Code Playgroud)
代码预计会起作用.但是,当它到达"C:\\Documents and Settings"
Windows 7计算机上的文件夹时,catch块会捕获"拒绝访问"错误(我期望).我想要做的是继续使用系列中的下一个文件夹.
所以问题是,我怎样才能在C#中实现这一目标?
我的研究显示了使用TRY ... CATCH块的常见观点,但它并没有告诉我如何做一些如上所述我想做的事情.
注意:我也尝试修改代码以检查属性如下,但它也失败了.
private void PopulateTree(string dir, TreeNode node)
{
try
{
// get the information of the directory
DirectoryInfo directory = new DirectoryInfo(dir);
if (directory.Attributes == FileAttributes.ReparsePoint || directory.Attributes == FileAttributes.System)
{
Console.Write("Access denied to folder.");
}
else
{
// 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 add these as nodes
foreach (FileInfo f in directory.GetFiles())
{
// create a new node
TreeNode t = new TreeNode(f.Name);
// add it to the "master"
node.Nodes.Add(t);
}
}
}
catch (System.Exception e)
{
MessageBox.Show(e.Message, "Error Loading Directories", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
Run Code Online (Sandbox Code Playgroud)
将try/catch块移动到foreach循环中,因此您可以在try块中使用填充代码.这样,遇到异常时,您不会退出循环.
foreach(var item in col)
{
try
{
//do stuff with item
}
catch
{
//yes, this is empty, but in this case it is okay as there is no other way
}
}
Run Code Online (Sandbox Code Playgroud)