0

I'm loading a treeview with directories and it's sub directories. My call to:

string[] dirs = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

returns all the directories i want and some i do not... like the inaccessible/virtual 'My Music', 'My Videos', etc...I of course cannot do any recursion in these directories due to the Library structure (Access denied)...

How can i avoid populating these inaccessible directories? I could iterate through the array and remove the unwanted directories if the OS is Vista or 7 and leave be for XP... but i wanted to know if there is a more 'elegant' solution to this?

with Wim's help i came up with this:

    private List<string> MyDocuments()
    {
        List<string> dirs = new List<string>(Directory.GetDirectories(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));

        for (int i = 0; i < dirs.Count-1; i++)
        {
            DirectoryInfo di = new DirectoryInfo(dirs[i]);
            if (di.Attributes.HasFlag(FileAttributes.ReparsePoint))
                dirs.RemoveAt(i);
        }

        return dirs;
    }
devHead
  • 794
  • 1
  • 15
  • 38
  • what do you mean by "inaccessible"? – Wim Ombelets Jan 08 '13 at 19:28
  • the structure returned contains "My Documents\\My Music" .... which is vitual on vista and 7... if you try to access anything in that path you get access violations... – devHead Jan 08 '13 at 19:31
  • i should say "paths" returned...not structure... – devHead Jan 08 '13 at 19:33
  • that's most likely a rights issue. Make sure you're running Visual Studio as Administrator, then run/debug again. SpecialFolders shouldn't give you a hard time anymore. – Wim Ombelets Jan 08 '13 at 20:11
  • No Wim... It's not access rights... if your running windows vista or 7 use the above code and see that it return "My Music", which doesnt reside in "My Documents" on Vista and 7...has something to do with Library structure... – devHead Jan 08 '13 at 20:15

1 Answers1

1

These directories seem to be both hidden and have a ReparsePoint attribute (requiring them to be empty, read this for more info from msdn and What is the best way to check for reparse point in .net (c#)? to see how it's done).

I can appreciate the need to search for elegant code, but the thing is, you could iterate over each directory and check for this attribute, subsequently skipping adding it to the array or list of directories but imho that's less elegant than iterating the dirs array, catching the exception and removing the entry. So, in short, i'd stick with:

List<string> dirs = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)).ToList();
string[] mySubDirs;

for (int i = 0; i < dirs.Count-1; i++)
{
    try
    {
        mySubDirs = Directory.GetDirectories(dirs[i]);
    }
    catch (Exception)
    {
        dirs.RemoveAt(i);
    }
}
Community
  • 1
  • 1
Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55