.net 从UserPrincipal获取额外的ad属性

.net 从UserPrincipal获取额外的ad属性,.net,active-directory,userprincipal,.net,Active Directory,Userprincipal,我使用以下代码通过登录名获取用户的全名: public View GetUser(string sUser) { View oView = new View(); oView.User = sUser.ToUpper(); using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "varner.no")) {

我使用以下代码通过登录名获取用户的全名:

public View GetUser(string sUser)
    {
        View oView = new View();
        oView.User = sUser.ToUpper();

        using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "varner.no"))
        {
            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, oView.User);
            oView.Name = oUserPrincipal.DisplayName;

            return oView;
        }
    }
}

但我还需要从代码中获取其他属性。在这种情况下,我需要ad中的“ipPhone”属性。这是可能的,还是我需要使用DirectoryEntry中的DirectorySearcher?

您可以通过扩展UserPrincipal来实现。您将在下面找到一个简短的示例,并在中找到更多信息

class DSPrincipals
  {
    static void Main(string[] args)
    {
      /* Retreiving a principal context
       */
      PrincipalContext domainContextMonou = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "ou=Monou,dc=dom,dc=fr", "jpb", "pass@1w0rd01");


      /* Create a user principal object
       */
      slxUser aSlxUser = new slxUser(domainContextMonou, "W.Zeidan", "pass@1w0rd01", true);

      /* assign some properties to the user principal
       */
      aSlxUser.GivenName = "Wessam";
      aSlxUser.Surname = "Zeidan";
      aSlxUser.streetAddress = "Add1";


      /* Force the user to change password at next logon
       */
      aSlxUser.ExpirePasswordNow();

      /* save the user to the directory
       */
      aSlxUser.Save();


      Console.ReadLine();
    }
  }

  [DirectoryObjectClass("user")]
  [DirectoryRdnPrefix("CN")]
  class slxUser : UserPrincipal
  {
    public slxUser(PrincipalContext context)
      : base(context) { }

    public slxUser(PrincipalContext context, string samAccountName, string password,  bool enabled ) : base(context, samAccountName, password, enabled)
    {
    }

    [DirectoryProperty("streetAddress")]
    public string streetAddress
    {
      get
      {
        object[] result = this.ExtensionGet("streetAddress");
        if (result != null)
        {
          return (string)result[0];
        }
        else
        {
          return null;
        }
      }
      set { this.ExtensionSet("streetAddress", value); }
    }
  }