I am using the code below to get the Files and the SubDirectories of a directory and then populate a TreeView control. I am getting an UnauthorizedAccessException exception. I tried to handle it using a try and catch but in vain...
void GetFilesAndSubDirs(DirectoryInfo root, TreeNodeCollection nodes)
{
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;
try
{
files = root.GetFiles("*.*");
subDirs = root.GetDirectories();
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show(e.Message);
}
catch (DirectoryNotFoundException e)
{
MessageBox.Show(e.Message);
}
TreeNode parent = FindNode(root.Name, nodes);
if (files != null)
{
foreach (FileInfo fiInfo in files)
{
TreeNode fileNode = new TreeNode(fiInfo.Name);
fileNode.ImageIndex = 1;
fileNode.SelectedImageIndex = 1;
parent.Nodes.Add(fileNode);
}
}
if (subDirs != null)
{
foreach (DirectoryInfo dirInfo in subDirs)
{
TreeNode dirNode = new TreeNode(dirInfo.Name);
dirNode.ImageIndex = 0;
dirNode.SelectedImageIndex = 0;
parent.Nodes.Add(dirNode);
GetFilesAndSubDirs(dirInfo, parent.Nodes);
}
}
}
UPDATE #1
When I comment the line of the recursive call, it works just fine.