如何从名字或姓氏(从一个输入文本框)获取AD用户名列表

时间:2013-10-14 11:46:56

标签: c# asp.net active-directory userprincipal

场景:用户在文本框中输入名称(可以是名字或姓氏),然后单击搜索按钮。系统应返回所有用户名(以及全名),无论第一个或姓氏与现有AD用户匹配。

问题:输入文本不会同时针对firstname和surname进行检查。

    List<string> GetUserDetails()
    {
        List<string> allUsers = new List<string>();
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myDomain",
                                                    "OU=ounit,dc=myDC,dc=com");

        UserPrincipal qbeUser = new UserPrincipal(ctx);

        qbeUser.GivenName = _UITxtUserName.Text;
        qbeUser.Surname = _UITxtUserName.Text;

        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
            foreach (var found in srch.FindAll())
            {

                allUsers.Add(found.DisplayName +"(" + found.SamAccountName+")");
            }

            allUsers.Sort();

        return allUsers;

    }

我可以看到问题出在 _UITxtUserName (文本框)中。但不确定如何解决。 使用.Net 3.5。

1 个答案:

答案 0 :(得分:3)

工作代码

List<string> GetUserDetails()
    {
        List<string> allUsers = new List<string>();
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myDomain",
                                                "OU=ounit,dc=myDC,dc=com");

        UserPrincipal qbeUser = new UserPrincipal(ctx);

        qbeUser.GivenName = _UITxtUserName.Text;

        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
        foreach (var found in srch.FindAll())
        {

            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");
        }
        qbeUser = null; 
        qbeUser = new UserPrincipal(ctx);

        qbeUser.Surname = _UITxtUserName.Text;

        PrincipalSearcher srch1 = new PrincipalSearcher(qbeUser);
        foreach (var found in srch1.FindAll())
        {

            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");
        }

        allUsers.Sort();

        return allUsers;
    }