C# 没有为active directory用户获取域用户组

C# 没有为active directory用户获取域用户组,c#,asp.net,active-directory,C#,Asp.net,Active Directory,我们使用以下代码获取active directory用户的组 StringCollection groups = new StringCollection(); try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password)) { //find user roles UserPrincipal user =

我们使用以下代码获取active directory用户的组

StringCollection groups = new StringCollection();

try
{
   using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password))
   {
      //find user roles
      UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginUserName);

      if (user != null)
      {
         DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
         object obGroups = de.Invoke("Groups");                        

         foreach (object ob in (IEnumerable)obGroups)
         {
            DirectoryEntry obGpEntry = new DirectoryEntry(ob);                            
            groups.Add(obGpEntry.Name);
         }    
      }
   }
}
catch (Exception e)
{
}
这几乎和预期的一样有效。但是,当我们使用
域用户
组检查用户时,该方法没有返回组名。有些用户只使用此
域用户
组,当我们为此类用户调用此方法时,它将返回一个空组


请提供任何建议。

众所周知,有文件记录的“遗漏”是,所谓的主要组不是从本代码中的
方法返回的。围绕这一点有一些相当隐晦的方法——或者尝试另一种方法:

如果您使用的是.NET 3.5及更高版本,则应检查
System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。请在此处阅读所有相关内容:

基本上,您可以定义域上下文并在AD中轻松找到用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // the call to .GetAuthorizationGroups() will return **all** groups that
   // user is a member of - including the primary group and all nested 
   // group memberships, too!
   var result = user.GetAuthorizationGroups();
}
新的S.DS.AM使得在广告中与用户和群组进行互动变得非常容易


更新:如果您坚持使用旧的遗留技术,请查看其中详细说明了如何在C#中获取广告帐户的主组。

是的,我之前使用过此选项,但随后出现了一个错误,如“无法检索域信息(1355)。”。我无法找出原因,所以我使用了旧技术。给定的链接现在显示404错误@mahesh:对不起,粘贴后有一个额外的字符-修复,立即生效。感谢链接。。但是我不明白那里解释的事情。我计划使用user.GetAuthorizationGroups()。但是我不明白为什么我会得到这个例外。。你能给我一些建议吗?谢谢你的链接。。我从这个链接得到了答案