Coming from the VB6 era, I was able to use the "on error resume next" in a relatively appropriate manner when recursing through directories on my system. If my "foreach" loop encountered a Permission Denied or Access Denied error, all I had to do was call the "resume next" statement.
In C# however, this does not exist and I appreciate why. However, it boggles my mind to figure out how this is possible in C#.
I am trying to recurse through the directories on my hard drive and populate a TreeView control.
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);
}
}
The code is expected to work. However, the very moment it reaches the "C:\Documents and Settings"
folder on a Windows 7 machine, the catch block traps the "Access Denied" error (which I expect). What I would like to do is CONTINUE on with the next folder in series.
So the question is, how can I make this possible in C#?
My research shows a common opinion to use a TRY...CATCH block, but it doesn't show me how to do something so simple as what I am wanting to do above.
NOTE: I also try modifying the code to check the attributes as follows but it too fails.
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);
}
}
See Question&Answers more detail:
os