简体   繁体   中英

Retrieving custom Active Directory properties of users

I've been trying to retrieve two custom properties that are set on our Active Directory users, but it seems like I keep getting a constant list of Properties (tested over 2 different AD servers)

Assuming the properties I'm trying to fetch are prop1 and prop2 , What am I doing wrong in the following code:

        List<String> nProps = new List<string>();

        DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");
        foreach (DirectoryEntry child in directoryEntry.Children)
        {
            // No filtering; ignore schemes that are not User schemes
            if (child.SchemaClassName == "User")
            {
                foreach (var sVar in child.Properties.PropertyNames)
                    nProps.Add(sVar.ToString());

                break;
            }
        }

nProps does not contain ANY of my custom properties (not prop1 nor prop2 )

(it does contain other properties, like BadPasswordAttempts, Username, etc)

Any ideas?

Are you sure your properties are set? if they are not set, they are not gonna be listed as properties.

If you're looking for specific properties, I'd recommend you to use DirectorySearcher

The following example is getting the company property of a given user. Note that you verify if the property exists first, then you extract it.

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");

//Create a searcher on your DirectoryEntry
DirectorySearcher adSearch= new DirectorySearcher(directoryEntry);
adSearch.SearchScope = SearchScope.Subtree;    //Look into all subtree during the search
adSearch.Filter = "(&(ObjectClass=user)(sAMAccountName="+ username +"))";    //Filter information, here i'm looking at a user with given username
SearchResult sResul = adSearch.FindOne();       //username is unique, so I want to find only one

if (sResult.Properties.Contains("company"))     //Let's say I want the company name (any property here)
{
    string companyName = sResult.Properties["company"][0].ToString();    //Get the property info
}

Though not a direct answer to your question, following is what we use:

        public static string GetProperty(string adUserId, string domain, string lDAPLoginId, string lDAPPassword, string propertyName)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, lDAPLoginId, lDAPPassword);
            UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, adUserId);

            string result = "";

            if (up != null)
            {
                result = PrincipalGetProperty(up, propertyName);
            }

            return result;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM