How to get Active Directory Attributes not represented by the UserPrincipal class

后端 未结 3 1182
自闭症患者
自闭症患者 2020-12-09 03:02

What I mean is that right now I am using System.DirectoryServices.AccountManagement and if I use UserPrincipal class I only see the Name, Middle Name, etc

so in my c

3条回答
  •  北海茫月
    2020-12-09 03:44

    up.Mobile would be perfect, but unfortunately, there's no such method in the UserPrincipal class, so you have to switch to DirectoryEntry by calling .GetUnderlyingObject().

    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());
        }
    }
    

提交回复
热议问题