如何获取UserPrincipal类未表示的Active Directory属性

我的意思是,现在我正在使用System.DirectoryServices.AccountManagement,如果我使用UserPrincipal类,我只看到名称,中间名等

所以在我的代码中它就像

UserPrincipal myUser = new UserPrincipal(pc); myUser.Name = "aaaaaa"; myUser.SamAccountName = "aaaaaaa"; . . . . myUser.Save(); 

我怎样才能看到像移动或信息这样的属性?

正确的方法是使用PrincipalExtensions扩展您所使用的PrincipalExtensions ,并使用ExtensionSetExtensionGet方法,如此处所述。

在这种情况下,您需要更深入一级 – 返回到DirectoryEntry – 通过从用户主体中获取它:

 DirectoryEntry de = (myUser.GetUnderlyingObject() as DirectoryEntry); if(de != null) { // go for those attributes and do what you need to do } 

up.Mobile是完美的,但不幸的是,UserPrincipal类中没有这样的方法,所以你必须通过调用.GetUnderlyingObject()来切换到DirectoryEntry。

 static void GetUserMobile(PrincipalContext ctx, string userGuid) { try { UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, userGuid); DirectoryEntry up_de = (DirectoryEntry)up.GetUnderlyingObject(); DirectorySearcher deSearch = new DirectorySearcher(up_de); deSearch.PropertiesToLoad.Add("mobile"); SearchResultCollection results = deSearch.FindAll(); if (results != null && results.Count > 0) { ResultPropertyCollection rpc = results[0].Properties; foreach (string rp in rpc.PropertyNames) { if (rp == "mobile") Console.WriteLine(rpc["mobile"][0].ToString()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }