2012-05-23 2 views
1

사용자가 속한 모든 Active Directory 응용 프로그램 그룹을 나열하려고합니다. 하지만 나는 아무것도 없어.사용자가 속한 모든 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

당신이 .NET 3.5 및 최대에 있다면, 당신은 System.DirectoryServices.AccountManagement (S.DS.AM) 네임 스페이스를 확인해야합니다. 여기에 대한 모든 읽기 :

// 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); 
    } 
} 

을 : MSDN docs on System.DirectoryServices.AccountManagement

기본적으로

+0

디버깅 중에 결과를 확인할 수 있도록 Principal 그룹을 문자열 목록으로 변환 할 수 있습니까? –

+0

@Love :'group.Name'을 보면 그룹의 이름을 알 수 있습니다 - 예. –

+0

모든 그룹이 아닌 일부 그룹 만 반환했습니다. 그리고 "NoMatchingPrincipalException occurred"예외가 발생했습니다. –

관련 문제