Search code examples
.netfile-ioattributesdirectoryinfogetdirectories

DirectoryInfo.GetDirectories() and attributes


I am using DirectoryInfo.GetDirectories() recursively to find the all the sub-directories under a given path. However, I want to exclude the System folders and there is no clear way for that. In FindFirstFile/FindNextFile things were clearer with the attributes.


Solution

  • @rslite is right, .NET doesn't give such filtering out-of-box, but it's not hard to implement:

    static IEnumerable<string> GetNonSystemDirs(string path)
    {
        var dirs = from d in Directory.GetDirectories(path)
                   let inf = new DirectoryInfo(d)
                   where (inf.Attributes & FileAttributes.System) == 0
                   select d;
    
        foreach (var dir in dirs)
        {
            yield return dir;
            foreach (var subDir in GetNonSystemDirs(dir))
            {
                yield return subDir;
            }
        }
    }
    

    MSDN links:

    FileSystemInfo.Attributes Property

    FileAttributes Enumeration