2010-11-16 88 views
1

在我的Active Directory(my.domain)中,我有很多組(UserGrp1,UserGrp2等),它們有很多用戶。用戶可以存在於多個組中。我目前的代碼允許我使用GroupPrincipal類來查找組,然後從那裏獲取該組的所有成員(請參閱下面的代碼)。 但是,我真正需要的是找到用戶所屬的所有組。例如,我有一個名爲Joe Test的域用戶(sAMAccountName = JOETEST),我需要找到他所屬的所有組。做這個的最好方式是什麼?通過GroupPrincipal查找用戶

如果我循環遍歷GetMembers()方法返回的所有成員,我可以確定用戶是否屬於一個組(如下所示),但這對我來說似乎效率低下,如果沒有更高效的方法,我會感到驚訝辦法。

using (PrincipalContext ctx = new PrincipalContext(
    ContextType.Domain, "my.domain", "DC=my,DC=domain")) { 

    if (ctx != null) { 
    using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, "UserGrp1")) { 
     // Get all group members 
     PrincipalSearchResult<Principal> psr = gp.GetMembers(); 
     foreach (Principal p in psr) { 
     // other logic 
     } 
    } 
    } 
} 

在此先感謝您提供的任何幫助。

回答

3

做它用UserPrincipal.GetGroups();

對於一個完整的代碼在這裏是

/// <summary> 
/// Gets a list of the users group memberships 
/// </summary> 
/// <param name="sUserName">The user you want to get the group memberships</param> 
/// <returns>Returns an arraylist of group memberships</returns> 
public ArrayList GetUserGroups(string sUserName) 
{ 
    ArrayList myItems = new ArrayList(); 
    UserPrincipal oUserPrincipal = GetUser(sUserName); 

    PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups(); 

    foreach (Principal oResult in oPrincipalSearchResult) 
    { 
     myItems.Add(oResult.Name); 
    } 
    return myItems; 
} 



/// <summary> 
/// Gets a certain user on Active Directory 
/// </summary> 
/// <param name="sUserName">The username to get</param> 
/// <returns>Returns the UserPrincipal Object</returns> 
public UserPrincipal GetUser(string sUserName) 
{ 
    PrincipalContext oPrincipalContext = GetPrincipalContext(); 

    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName); 
    return oUserPrincipal; 
} 


/// <summary> 
/// Gets the base principal context 
/// </summary> 
/// <returns>Retruns the PrincipalContext object</returns> 
public PrincipalContext GetPrincipalContext() 
{ 
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword); 
    return oPrincipalContext; 
} 

或一個完整的AD參考去here

+0

謝謝,Raymund!不能相信我以某種方式錯過了UserPrincipal中的GetGroups()方法。它正盯着我的臉! – Jagd 2010-11-18 17:08:14

+0

哈哈!我不認爲這發生在每個人身上 – Raymund 2010-11-18 18:57:55