How I get Active Directory User Properties with System.DirectoryServices.AccountManagement Namespace?

时光怂恿深爱的人放手 提交于 2019-12-09 17:07:34

问题


I want do get Active Directory Properties from a user and I want to use System.DirectoryServices.AccountManagement.

my code:

public static void GetUserProperties(string dc,string user) 
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
            UserPrincipal u = UserPrincipal.FindByIdentity(ctx, user);

            string firstname = u.GivenName;
            string lastname = u.Surname;
            string email = u.EmailAddress;
            string telephone = u.VoiceTelephoneNumber;

            ...//how I can get company and other properties?
        }

回答1:


You can transition into the DirectoryServices namespace to get any property you need.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, user);

string firstname = u.GivenName;
string lastname = u.Surname;
string email = u.EmailAddress;
string telephone = u.VoiceTelephoneNumber;
string company = String.Empty;

...//how I can get company and other properties?
if (userPrincipal.GetUnderlyingObjectType() == typeof(DirectoryEntry))
{
    // Transition to directory entry to get other properties
    using (var entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject())
    {
        if (entry.Properties["company"] != null)
            company = entry.Properties["company"].Value.ToString();
    }
}



回答2:


If you want to change the proppertie dont forget to call userPrincipal.save() after you changed the value.

entry.Properties["company"].value = company;
userPrincipal.save();


来源:https://stackoverflow.com/questions/14278274/how-i-get-active-directory-user-properties-with-system-directoryservices-account

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