2010-06-07 53 views
0

我有以下代碼。我得到一個用戶的目錄條目(strpath)。 然後我得到用戶列出的組。在活動目錄中查找組大小

我怎樣才能獲得每組用戶的數量?

DirectoryEntry myDE = new System.DirectoryServices.DirectoryEntry(strpath); 
object obGroups = myDE.Invoke("Groups"); 
foreach (object ob in (IEnumerable)obGroups) 
{ 
    DirectoryEntry obGpEntry = new DirectoryEntry(ob); 
    GroupsListBox.Items.Add(obGpEntry.Name); 
} 

回答

1

如果你在.NET 3.5(或可以升級到它),有一個大規模擴展System.DirectoryServices.AccountManagement命名空間,使得管理用戶,組和他們的成員輕鬆許多的這些作業。

查看MSDN文章Managing Directory Security Principals in the .NET Framework 3.5瞭解S.DS.AM的介紹。

你可以得到一個用戶主要是這樣的:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"); 

UserPrincipal user = UserPrincipal.FindByIdentity("some user name"); 

PrincipalSearchResult<Principal> userGroups = user.GetGroups(); 

foreach (Principal p in myGroups) 
{ 
    GroupPrincipal gp = (p as GroupPrincipal); 

    if (gp != null) 
    { 
     int memberCount = gp.Members.Count; 
    } 
} 

這種方式,您可以枚舉所有組給定的用戶,並列舉出這些羣體,你可以找出有多少成員(用戶和其他組)每個組都有。