11

我想从用户那里获取 Active Directory 属性,并且我想使用System.DirectoryServices.AccountManagement.

我的代码:

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?
        }
4

2 回答 2

21

您可以转换到 DirectoryServices 命名空间以获取您需要的任何属性。

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();
    }
}
于 2014-03-25T17:04:57.883 回答
3

如果您想更改属性,请不要忘记在更改值后调用 userPrincipal.save()。

entry.Properties["company"].value = company;
userPrincipal.save();
于 2018-11-27T13:25:04.157 回答