How to get all user from LDAP in C# Using DirectoryEntry() or PrincipalContext()?

Viewed 338
private void ADQuery()
{
    try
    {
        string connString = "LDAP://10.0.10.11/dc=abcd,dc=ac,dc=in";//demo url

        string username = "cn=admin,dc=abcd,dc=ac,dc=in";
        string name = "cn=admin,dc=abcd,dc=ac,dc=in";
        string password = "secrate";

        string name2 = "10.0.10.11\admin";//  domain\username
            
        DirectoryEntry de = new DirectoryEntry(connString, name2, "secrate", AuthenticationTypes.Secure);
          
        var search = new DirectorySearcher(de)
                         {   
                             Filter = "(&(ou=employee)(objectClass=inetOrgPerson))"
                         };
        search.SearchScope = SearchScope.Subtree;

        // error thrown by this statement
        SearchResult results = search.FindOne();

        if (results != null)
        {
            string email = results.Properties["mail"].ToString();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

I get this error:

Server Error in '/' Application.

A local error has occurred.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:

System.DirectoryServices.DirectoryServicesCOMException: A local error has occurred

1 Answers

Looking through your code, the only problem that stands out to me is your filter:

Filter = "(&(ou=employee)(objectClass=inetOrgPerson))"

In Active Directory, the inetOrgPerson class is not used for users. If you want to find user objects, you should be using this as a filter:

Filter = "(&(objectClass=user)(objectCategory=person))"

You also cannot filter on ou like you are trying to. To limit your search to a specific OU, use that OU in your LDAP string of the DirectoryEntry object that you're using for the SearchRoot. In your case, it's your connString variable:

string connString = "LDAP://10.0.10.11/OU=employee,dc=abcd,dc=ac,dc=in";

Also, AuthenticationTypes.Secure is the default AuthenticationType, so you don't need to specify it in the constructor:

DirectoryEntry de = new DirectoryEntry(connString, name2, "secrate", AuthenticationTypes.Secure);

Likewise, Subtree is the default SearchScope, so you don't need this line:

search.SearchScope = SearchScope.Subtree;
Related