2011-08-30 107 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); 
} 
相關問題