如何在 C# 中使用 UserPrincipal 获取 Active Directory 中地址的详细信息

How to get details of address in Active Directory using UserPrincipal in C#

我正忙于在 运行 我的 Windows 服务器上的 GUI 应用程序中创建搜索功能,以添加、删除、更新和搜索用户。 我几乎完成了应用程序的构建,但我无法解决从其他 属性 获取详细信息的问题,这在 UserPrincipal 中未提供,例如 'Address' 属性。 我怎样才能进入 属性?

我尝试了很多编码风格来进入给定的 属性 'Address',但它仍然不起作用。

代码如下:

private void ListOfUsers(String ou)
{
    List<string> users = new List<string>();

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "EMRE", "OU=" + ou + ",dc=emre,dc=han");
    UserPrincipal qbeUser = new UserPrincipal(ctx);
    PrincipalSearcher search = new PrincipalSearcher(qbeUser);


    foreach (UserPrincipal user in search.FindAll())
    {
        users.Add(user.UserPrincipalName);
        users.Add("********");
        users.Add(user.GivenName);
        users.Add(user.Surname);

        if (user.GetUnderlyingObjectType() == typeof(DirectoryEntry))
        {
            using (var entry = (DirectoryEntry)user.GetUnderlyingObject())
            {
                if (entry.Properties["Address"] != null)
                    users.Add(entry.Properties["Street"].Value.ToString());
            }
        }
        users.Add(user.VoiceTelephoneNumber);
        users.Add(user.EmailAddress);
        users.Add(ou);

    }

    string[] row = users.ToArray();
    var listViewItem = new ListViewItem(row);
    lstStudents.Items.Add(listViewItem);

}

即使 属性 不是 null

,我总是会返回 null

你要的属性其实是调用了streetAddress. You can also use Properties.Contains来检查值是否存在(虽然效果真的和检查null一样,只是读起来更方便)

if (entry.Properties.Contains("streetAddress"))
    users.Add(entry.Properties["streetAddress"].Value.ToString());

就个人而言,我喜欢直接使用 DirectoryEntry/DirectorySearcher,而不是 UserPrincipal/PrincipalSearcher,因为它让我可以更好地控制它正在做什么,这可以转化为更好的性能。我在这里写了一点:Active Directory: Better performance