GetAuthorizationGroups()抛出异常

Alo*_*lok 13 c# active-directory

PrincipalContext context = new PrincipalContext(ContextType.Domain, "ipofmachine", "DC=xyz,DC=org", "username", "Password");

UserPrincipal userPrinciple = UserPrincipal.FindByIdentity(context, "User0"); 
var groups = userPrinciple.GetAuthorizationGroups();

if (userPrinciple != null)
{
    foreach (GroupPrincipal gp in groups)
    {
        //some thing
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要给予任何许可吗?在一些博客中,我了解到,如果没有设置为包含SID历史记录的用户,那么这将正常工作(但我认为您无法编辑组的sid值)

C. *_*alt 16

我发现将域用户添加到本地组时会出现问题,但稍后该域用户将从Active Directory中删除.该本地组的状态是,而不是显示为成员的域用户名,而是使用SID.

但!

这个SID在Active Directory中不再存在,导致事情变得繁荣.

当然,弹出NoMatchingPrincipalException可能还有很多其他原因,因此这段代码为此提供了一种解决方法.它来自MSDN上的一篇很棒的帖子.以下代码是此处的修改版本:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/9dd81553-3539-4281-addd-3eb75e6e4d5d/getauthorizationgroups-fails-with-nomatchingprincipalexception

    public static IEnumerable<Principal> getAuthorizationGroups(UserPrincipal user)
    {
        PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
        List<Principal> ret = new List<Principal>();
        var iterGroup = groups.GetEnumerator();
        using (iterGroup)
        {
            while (iterGroup.MoveNext())
            {
                try
                {
                    Principal p = iterGroup.Current;
                    Console.WriteLine(p.Name);
                    ret.Add(p);
                }
                catch (NoMatchingPrincipalException pex)
                {
                    continue;
                }
            }
        }
        return ret;
    }
Run Code Online (Sandbox Code Playgroud)