2012-02-28 127 views
3

我正在查看DirectoryServices名称空间,我试图获取AD中所有组的列表并将它们加载到列表框中。如何查询所有组和组成员的Active Directory?

当我选择一个组时,我希望它填充一个带有管理员姓名的文本框以及另一个包含所有用户分配给该组的列表框。我很难在这个过程中缠绕我的头脑。有人可以帮我吗?

如果我得到一个完整的例子,我相当肯定,我会更好地理解更大的图景。 TIA

+1

您是否浏览过该参考资料:http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C# – Dan 2012-02-28 18:24:31

+0

是的,但我并不完全确定哪个那些适用于我或如何将它们应用于我的目标 – Sinaesthetic 2012-02-28 19:02:23

回答

9

如果你在.NET 3.5或更高版本上运行,你可以使用一个PrincipalSearcher和“查询通过例如”主要做你的搜索:如果您尚未

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a GroupPrincipal 
GroupPrincipal qbeGroup = new GroupPrincipal(ctx); 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    GroupPrincipal foundGroup = found as GroupPrincipal; 

    if(foundGroup != null) 
    { 
     // do whatever you need to do, e.g. put name into a list of strings or something 
    } 
} 

- 绝对看MSDN文章Managing Directory Security Principals in the .NET Framework 3.5这很好地说明如何使新功能的最佳使用System.DirectoryServices.AccountManagement

当你有一定的团体,你可以很容易地通过使用获得其所有组成员:

// find the group in question (or load it from e.g. your list) 
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere"); 

// if found.... 
if (group != null) 
{ 
    // iterate over members 
    foreach (Principal p in group.GetMembers()) 
    { 
     Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName); 
     // do whatever you need to do to those members 
    } 
} 
2

我想出了类似的使用System.DirectoryServices.AccountManagement命名空间marc_s东西:

PrincipalContext context = new PrincipalContext(ContextType.Domain); 
GroupPrincipal queryPrincipal = new GroupPrincipal(context); 

using (PrincipalSearcher searcher = new PrincipalSearcher(queryPrincipal)) 
using (PrincipalSearchResult<Principal> allPrincipals = searcher.FindAll()) 
    foreach (GroupPrincipal groupPrincipal in allPrincipals.OfType<GroupPrincipal>()) 
    { 
     // Process group... 

     foreach (UserPrincipal userPrincipal in groupPrincipal.Members.OfType<UserPrincipal>()) 
     { 
      // Process group member... 
     } 
    } 

UserPrincipal class似乎并没有暴露,将允许您确定用户是否和/或拥有校董的成员,但你仍然可以做到这一点通过获取DirectoryEntry用户:

DirectoryEntry userEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry; 

if (userEntry != null) 
{ 
    bool isManager = userEntry.Properties["directReports"].Count > 0; 
    bool isManaged = userEntry.Properties["manager"].Count > 0; 

    // Perform further processing... 
} 

你需要一些额外的逻辑,不过,以确定用户是否是公司的经理,你目前正在观察,而比其他一些组织。也许检查directReports属性以查看包含在其中的任何用户是否是当前组的成员。

相关问题