Retrieving custom Active Directory properties of users

ε祈祈猫儿з 提交于 2019-12-18 09:23:45

问题


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?


回答1:


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
}



回答2:


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;
        }


来源:https://stackoverflow.com/questions/8927309/retrieving-custom-active-directory-properties-of-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!