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

天涯浪子 提交于 2019-11-26 20:23:33

问题


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 codes it like

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

How would I see the attribute like mobile or info?


回答1:


The proper way of doing it is by using PrincipalExtensions where you extend the Principal you are after and use the methods ExtensionSet and ExtensionGet as explained here.




回答2:


In this case, you need to go one level deeper - back into the bowels of DirectoryEntry - by grabbing it from the user principal:

using (DirectoryEntry de = myUser.GetUnderlyingObject() as DirectoryEntry)
{
    if (de != null)
    {
        // Go for those attributes and do what you need to do...
        var mobile = de.Properties["mobile"].Value as string;
        var info = de.Properties["info"].Value as string;
    }
}



回答3:


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


来源:https://stackoverflow.com/questions/3929561/how-to-get-active-directory-attributes-not-represented-by-the-userprincipal-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!