MAC
MAC

Reputation: 6577

Getting All OUs from a Active Directory

Is there any direct method for getting all OUs coming under in an Active Directory? I had tried the following code, and i am getting Com Exception (Invalid operation) at

ouSearch.FindAll()

My code is shown below.

public static List<string> GetAllOus(string ldapServer, string ldapUserName, string ldapPassWord)
    {

        List<string> orgUnits = new List<string>();
        string defaultNamingContext;

        DirectoryEntry rootDSE = new DirectoryEntry(ldapServer + "/dc=server-dc,dc=com", ldapUserName, ldapPassWord, AuthenticationTypes.Anonymous);
        //defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();

        //DirectoryEntry defaultentry = new DirectoryEntry("LDAP://" + defaultNamingContext);

        DirectorySearcher ouSearch = new DirectorySearcher(rootDSE,
                                             "(objectClass=organizational-Unit)",
                                             null, SearchScope.Subtree);

        foreach (SearchResult resEnt in ouSearch.FindAll())
        {
            string OUName = resEnt.GetDirectoryEntry().Name;
            orgUnits.Add(OUName);
        }

        return orgUnits;
    }

Please help me to resolve this issue.

Thanks in advance

Upvotes: 0

Views: 2768

Answers (1)

Sean
Sean

Reputation: 1822

use (objectClass=organizationalUnit) instead of (objectClass=organizational-Unit)

Upvotes: 2

Related Questions