返回用户所属的所有Active Directory应用程序组的列表

我想列出用户所属的所有Active Directory应用程序组。 但是我什么也没得到。

谢谢你的build议。

public List<string> GetGroups(string strUserName) { DirectoryEntry objADAM = default(DirectoryEntry); // Binding object. DirectoryEntry objGroupEntry = default(DirectoryEntry); // Group Results. DirectorySearcher objSearchADAM = default(DirectorySearcher); // Search object. SearchResultCollection objSearchResults = default(SearchResultCollection); // Results collection. string strPath = null; // Binding path. List<string> result = new List<string>(); // Construct the binding string. strPath = "LDAP://CHCAD.abc/DC=abc"; //Change to your ADserver // Get the AD LDS object. try { objADAM = new DirectoryEntry(strPath); objADAM.RefreshCache(); } catch (Exception e) { throw e; } // Get search object, specify filter and scope, // perform search. try { objSearchADAM = new DirectorySearcher(objADAM); objSearchADAM.Filter = "(&(objectClass=group)(samaccountname=" + strUserName + "))"; objSearchADAM.SearchScope = SearchScope.Subtree; objSearchResults = objSearchADAM.FindAll(); } catch (Exception e) { throw e; } // Enumerate groups try { if (objSearchResults.Count != 0) { foreach (SearchResult objResult in objSearchResults) { objGroupEntry = objResult.GetDirectoryEntry(); result.Add(objGroupEntry.Name); } } else { throw new Exception("No groups found"); } } catch (Exception e) { throw new Exception(e.Message); } return result; } 

如果您使用.NET 3.5或更高版本,则应检出System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 在这里阅读所有信息:

  • 管理.NET Framework 3.5中的目录安全主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

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

 // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find a user - this will search for DN and samAccountName and display name and a few more UserPrincipal user = UserPrincipal.FindByIdentity(ctx, strUserName); if(user != null) { // if user is found - get the groups that user belongs to PrincipalSearchResult<Principal> authGroups = user.GetAuthorizationGroups(); List<string> groupNames = new List<string>(); foreach(Principal group in authGroups) { // do something with the groups - like add their name to a List<string> groupNames.Add(group.Name); } } 

新的S.DS.AM使得与AD中的用户和群组玩起来真的很容易!

PS:否则,如果你不能切换到S.DS.AM,你应该检查我的答案另一个StackOverflow问题 ,处理相同的问题。 基本上只是检查你的DirectoryEntry对象的memberOf属性。