0

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

MAC
  • 6,277
  • 19
  • 66
  • 111
  • 1
    What value does your `ldapServer` have?? – marc_s May 29 '13 at 09:41
  • @marc_s: its contains the value like, LDAP://192.168.2.5 (AD Server) – MAC May 29 '13 at 09:43
  • OK, just make absolutely sure that the `LDAP://` part is **capitalized** (don't use `ldap://` or `Ldap://` or anything like that..) – marc_s May 29 '13 at 09:44
  • 2
    I think you should use (objectClass=organizationalUnit) and not (objectClass=organizational-Unit). – Hans May 29 '13 at 09:45
  • ya.. its fully capitalized. – MAC May 29 '13 at 09:45
  • Now its getting An operations error occurred (DirectoryServiceCOMexception) – MAC May 29 '13 at 09:50
  • Did you already try AuthenticationTypes.Secure instead of AuthenticationTypes.Anonymous? – Hans May 29 '13 at 09:59
  • @Hans: After changing the authenticationType to Secure, i am getting this error. A referral was returned from the server (DirectoryServiceCOMexception) – MAC May 29 '13 at 10:53
  • @MAC: What's the name of your domain? Is server-dc really your domain name or the name of your domain controller? – Hans May 29 '13 at 11:36
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30825/discussion-between-mac-and-hans) – MAC May 29 '13 at 11:40

1 Answers1

2

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

Sean
  • 1,806
  • 1
  • 13
  • 15