C#LDAP查询有时会失败

时间:2012-12-04 10:41:49

标签: c# active-directory

我在程序中有这段代码,用于查询Windows域用户所属的组。

    public void GetGroupNames(string userName, List<string> result)
    {
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
        {
            UserPrincipal uPrincipal = UserPrincipal.FindByIdentity(pc, userName);
            if (uPrincipal != null)
            {
                PrincipalSearchResult<Principal> srcList = uPrincipal.GetGroups();
                foreach (Principal item in srcList)
                {
                    result.Add(item.ToString());
                }
            }
        }
    }

当我刚刚实现它并进行调试时,

UserPrincipal uPrincipal = UserPrincipal.FindByIdentity(pc, userName);

始终为空。 然后,我不得不关闭视觉工作室做其他事情。当我回来,打开视觉工作室时,这段代码才有效。几天前,组织中存在网络问题,在此期间我没有关闭我的电脑。在网络恢复正常后,我可以连接到网络正常,我可以远程桌面到服务器等,这证明Active Directory身份验证已经完成,但上面的代码无法找到给定名称的UserPrinical,例如我自己的。然后我重新启动电脑,代码工作正常。关于这个问题我很困惑。有人能够为此提供一个很好的解释吗?

1 个答案:

答案 0 :(得分:0)

UserPrincipal在跨域方案中存在一些已知错误。再次发生时,查看是否可以从您的计算机中解析组。当组成员无法解析SID时,我也遇到了问题。