Search code examples
c#active-directoryldapdirectorysearcher

Unable to get certain fields form LDAP users


I'm unable to get certain fields from user objects such as PasswordNeverExpires. Right now I'm cycling through every property returned by over 2000 users and my conditional breakpoint never breaks once, so I know it's not returning. If I break unconditionally the number of properties returned by this code is always 1. Our sever is Windows 2003 Server. I can get all the information I want from NetEnum commands. I've seen others claim that they can do this and I don't see what's different about my code. When I don't provide any properties to load, it grabs about 30-37 properties. Several of these properties I need and use.

    public void FetchUsers(string domainId, Sql sql)
    {
        var entry = new DirectoryEntry("LDAP://" + DomainControllerAddress, DomainPrefixedUsername, Password,
            AuthenticationType);

        var dSearch = new DirectorySearcher(entry)
        {
            Filter = "(&(objectClass=user)(!(objectclass=computer)))",
            SearchScope = SearchScope.Subtree,
            PageSize = 1000,

        };

        dSearch.PropertiesToLoad.Add("passwordneverexpires");

        var users = dSearch.FindAll();

        foreach (SearchResult ldapUser in users)
        {
            SaveUser(ldapUser, sql, domainId);
        }
    }

    private void SaveUser(SearchResult ldapUser, Sql sql, string domainId)
    {
        if (ldapUser.Properties.PropertyNames == null) return;

        foreach (string propertyName in ldapUser.Properties.PropertyNames)
        {
//I'm breaking here on the condition that propertyName != 'adspath' and it never breaks
            var v = ldapUser.Properties[propertyName];
        }

        return;
}

Solution

  • Few things:

    1. The base filter you have is very inefficient. Use this instead (&(objectCategory=person)(objectClass=user)).
    2. There's no property called passwordneverexpires. You'll need to check bit 13 in the userAccountControl mask on the user - see http://msdn.microsoft.com/en-us/library/aa772300%28v=vs.85%29.aspx for a list of values.
    3. You never break in to your loop because you're telling the client to only request one property.