1

我想列出用户所属的所有 Active Directory 应用程序组。但我一无所获。

谢谢你的建议。

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;
    } 
4

1 回答 1

4

如果您使用的是 .NET 3.5 及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM) 命名空间。在这里阅读所有相关信息:

基本上,您可以定义域上下文并在 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 问题的回答。基本上只需检查对象的memberOf属性DirectoryEntry

于 2012-05-23T20:43:16.153 回答