locked
Listing Organisational Units (OU'S) from Active Directory RRS feed

  • Question

  • User1132166131 posted

    Hi Guys,

    I have what is hopefully a quick question. I am writing a Web App that needs to be able to list out OU's and sub OU's from AD. I have done this in the past using LDAP. 

    For the user management side I am using the 'UserPrinciples' which I have found a lot easier to use, is there a similar Principle for Achieving the same thing or do we will still need to use the LDAP Method.

    Regards, 

    Sunday, October 6, 2019 10:21 AM

All replies

  • User1724605321 posted

    Hi tompark ,

    You could try appropriate  DirectorySearcher from System.DirectoryServices , please refer to below code samples :

    // connect to "RootDSE" to find default naming context
    DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
    
    string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();
    
    // bind to default naming context - if you *know* where you want to bind to - 
    // you can just use that information right away
    DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);
    
    // set up directory searcher based on default naming context entry
    DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);
    
    // SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
    // subtree = all OU's in the whole domain (can take **LONG** time!)
    ouSearcher.SearchScope = SearchScope.OneLevel;
    // ouSearcher.SearchScope = SearchScope.Subtree;
    
    // define properties to load - here I just get the "OU" attribute, the name of the OU
    ouSearcher.PropertiesToLoad.Add("ou");
    
    // define filter - only select organizational units
    ouSearcher.Filter = "(objectCategory=organizationalUnit)";
    
    // do search and iterate over results
    foreach (SearchResult deResult in ouSearcher.FindAll())
    {
        string ouName = deResult.Properties["ou"][0].ToString();
    }

    Code is from below thread with expatiation :

    https://stackoverflow.com/questions/13605618/how-to-get-list-of-ou-name-in-ad-using-domainname-using-c

    https://stackoverflow.com/a/5348657/5751404

    Best Regards,

    Nan Yu

    Monday, October 7, 2019 5:18 AM