views:

201

answers:

2

Hi,

I am populating a treeview control, c# visual studio 8, using this code:

private TreeNode TraverseDirectory(string path)
    {
        TreeNode result = new TreeNode(path);
        foreach (var subdirectory in Directory.GetDirectories(path))
        {
            result.Nodes.Add(TraverseDirectory(subdirectory));
        }

        return result;
    }

The trouble is that if I click on, say the c:/ drive I get an error on directories that I do not have permission to read. My question is, how do I avoid showing those directories that I do not have permission for? How would I test for that and then tell the app to ignore them?

Thanks R.

+1  A: 

For a simplistic approach:

TreeNode result;
try {
    string[] subdirs = Directory.GetDirectories(path);
    result = new TreeNode(path);
    foreach(string subdir in subdirs) {
        TreeNode child = TraverseDirectory(subdir);
        if(child != null) { result.Nodes.Add(child); }
    }
    return result;
} catch (FindTheSpecificException) {
    // ignore dir
    result = null;
}
return result;

personally I'd try and do some kind of lazy loading, but IIRC this involves adding dummy nodes with the standard TreeView.

Marc Gravell
Thanks Marc i'll have a go at this tomorrow as its getting late and the brain power is getting low... :)
flavour404
A: 

As for testing, I think this previous question covers it: http://stackoverflow.com/questions/265953/c-how-can-you-easily-check-if-access-is-denied-for-a-file

As for telling the app to ignore it, simply put your call to result.Nodes.Add() inside your test condition block, so if the permission does not exist, no node is added. If you decide to go with try...catch, make sure you're swallowing the right SecurityException, because there are other exceptions that could occur here, but that's it.

Jay
Thanks, i'll bear it in mind and have a go at it :)
flavour404