如何在C#中的Active Directory中的UserPrincipal对象上设置管理器属性

Rat*_*Stl 5 c# active-directory

我试图ManagerUserPrincipal这里记录的类型对象上设置属性:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms680857(v=vs.85).aspx

但不能简单地说

UserPrincipal.Manager = "some value" 
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释一下这是如何工作的吗?谢谢!

mar*_*c_s 9

UserPrincipalS.DS.AM命名空间中的基本功能不具有该属性 - 但您可以扩展用户主体类并添加所需的其他属性.

在这里阅读更多相关信息:

管理.NET Framework 3.5中的目录安全性主体
(本文末尾有关于可扩展性的部分)

这是代码:

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx : UserPrincipal
{
    // Inplement the constructor using the base class constructor. 
    public UserPrincipalEx(PrincipalContext context) : base(context)
    { }

    // Implement the constructor with initialization parameters.    
    public UserPrincipalEx(PrincipalContext context,
                         string samAccountName,
                         string password,
                         bool enabled) : base(context, samAccountName, password, enabled)
    {} 

    // Create the "Manager" property.    
    [DirectoryProperty("manager")]
    public string Manager
    {
        get
        {
            if (ExtensionGet("manager").Length != 1)
                return string.Empty;

            return (string)ExtensionGet("manager")[0];
        }
        set { ExtensionSet("manager", value); }
    }

    // Implement the overloaded search method FindByIdentity.
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
    }

    // Implement the overloaded search method FindByIdentity. 
    public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以找到并使用UserPrincipalEx具有.Manager您可以使用的属性的类:

UserPrincipalEx userEx = UserPrincipalEx.FindByIdentity(ctx, "YourUserName");

// the .Manager property contains the DN (distinguished name) for the manager of this user
var yourManager = userEx.Manager;
Run Code Online (Sandbox Code Playgroud)