Search code examples
c#winformswindows-7directory-structure.net

Windows 7 Libraries and Directory structure


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

Solution

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