2011-08-30 29 views

回答

30

如果您使用的是.NET 3.5及更高版本,则应检查System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读全部内容:

基本上,你可以定义域范围内,并可以轻松地查找用户和/或组AD:

// set up domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find the group in question 
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 
     UserPrincipal theUser = p as UserPrincipal; 

     if(theUser != null) 
     { 
      if(theUser.IsAccountLockedOut()) 
      { 
       ... 
      } 
      else 
      { 
       ... 
      } 
     } 
    } 
} 

的新的S.DS.AM可以很容易地与AD中的用户和群组玩耍!

+0

谢谢,我会检查一下。 –

+2

使用此方法的任何人的注意事项:这对传递组成员资格不起作用,即如果组B是A组的成员,并且用户C是组B的成员,则用户C将不会显示在结果中。 –

+0

在哪里指定域名,用户名和pswd? – Shesha

1

请你可以试试下面的代码。它使用Search Filter Syntax以递归方式在一个LDAP查询中获取所需内容。兴趣是查询在服务器上完成。我不确定它比@marc_s解决方案更快,但它存在,它可以在.NET 2.0(开始W2K3 SP2)上运行。

string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr"; 
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "test.2011"); 

/* To find all the users member of groups "Grp1" : 
* Set the base to the groups container DN; for example root DN (dc=societe,dc=fr) 
* Set the scope to subtree 
* Use the following filter : 
* (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X) 
* coupled with LDAP_MATCHING_RULE_BIT_AND on userAccountControl with ACCOUNTDISABLE 
*/ 
DirectorySearcher dsLookFor = new DirectorySearcher(deBase); 
dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=MonGrpSec,OU=MonOu,DC=dom,DC=fr)(userAccountControl:1.2.840.113556.1.4.803:=2))"; 
dsLookFor.SearchScope = SearchScope.Subtree; 
dsLookFor.PropertiesToLoad.Add("cn"); 

SearchResultCollection srcUsers = dsLookFor.FindAll(); 

/* Just to know if user is present in an other group 
*/ 
foreach (SearchResult srcUser in srcUsers) 
{ 
    Console.WriteLine("{0}", srcUser.Path); 
} 
相关问题