C# 如何使用 System.DirectoryServices.AccountManagement 命名空间获取 Active Directory 用户属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14278274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:17:29  来源:igfitidea点击:

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

c#propertiesactive-directoryprincipaluserprincipal

提问by Tarasov

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

我想从用户那里获取 Active Directory 属性,并且我想使用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?
        }

回答by user3460811

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

您可以转换到 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();
    }
}

回答by Pieter

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

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

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