gpt4 book ai didi

c# - 需要在 Catch block 后恢复 Try

转载 作者:太空狗 更新时间:2023-10-30 00:16:48 25 4
gpt4 key购买 nike

从 VB6 时代开始,当递归遍历我系统上的目录时,我能够以相对适当的方式使用“on error resume next”。如果我的“foreach”循环遇到权限被拒绝或访问被拒绝的错误,我所要做的就是调用“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);
}

}

代码应该可以工作。但是,就在它到达 Windows 7 计算机上的 "C:\\Documents and Settings" 文件夹的那一刻,catch block 捕获了“拒绝访问”错误(我预料到了)。我想做的是继续处理系列中的下一个文件夹。

所以问题是,如何在 C# 中实现这一点?

我的研究显示了使用 TRY...CATCH block 的普遍意见,但它没有告诉我如何做一些像我上面想做的那样简单的事情。

注意:我也尝试修改代码以如下检查属性,但它也失败了。

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);
}

}

最佳答案

将 try/catch block 移到 foreach 循环中,这样您就可以在 try block 中填充代码。这样,您就不会在遇到异常时退出循环。

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
}
}

关于c# - 需要在 Catch block 后恢复 Try,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com