2

我有一個域名myDomain.local的Active Directory,它下面有一個Distribution Group包含很多組。
如何讀取(以編程方式)所有這些子組以檢索其名稱列表?
以及如何優化查詢來篩選結果,以便它只檢索所有以Region結尾的組?
順便說一句,我使用的是C#.Net,ASP.Net和sharepoint,而我對AD沒有經驗。閱讀/過濾分發組的活動目錄的子組?

回答

1

這是我所做的解決方案;對於那些有興趣的人:

public ArrayList getGroups() 
{ 
    // ACTIVE DIRECTORY AUTHENTICATION DATA 
    string ADDomain = "myDomain.local"; 
    string ADBranchsOU = "Distribution Group"; 
    string ADUser = "Admin"; 
    string ADPassword = "password"; 

    // CREATE ACTIVE DIRECTORY ENTRY 
    DirectoryEntry ADRoot 
     = new DirectoryEntry("LDAP://OU=" + ADBranchsOU 
          + "," + getADDomainDCs(ADDomain), 
          ADUser, 
          ADPassword); 

    // CREATE ACTIVE DIRECTORY SEARCHER 
    DirectorySearcher searcher = new DirectorySearcher(ADRoot); 
    searcher.Filter = "(&(objectClass=group)(cn=* Region))"; 
    SearchResultCollection searchResults = searcher.FindAll(); 

    // ADDING ACTIVE DIRECTORY GROUPS TO LIST 
    ArrayList list = new ArrayList(); 
    foreach (SearchResult result in searchResults) 
    { 
     string groupName = result.GetDirectoryEntry().Name.Trim().Substring(3); 
     list.Add(groupName); 
    } 
    return list; 
} 

public string getADDomainDCs(string ADDomain) 
{ 
    return (!String.IsNullOrEmpty(ADDomain)) 
     ? "DC=" + ADDomain.Replace(".", ",DC=") 
     : ADDomain; 
} 
2

如果你在.NET 3.5(或可以升級到它),你可以使用System.DirectoryServices.AccountManagement命名空間中使用此代碼:

// create the "context" in which to operate - your domain here, 
// as the old-style NetBIOS domain, and the container where to operate in 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "cn=Distribution Group,dc=YourDomain,dc=local"); 

// define a "prototype" - an example of what you're searching for 
// Here: just a simple GroupPrincipal - you want all groups 
GroupPrincipal prototype = new GroupPrincipal(ctx); 

// define a PrincipalSearcher to find those principals that match your prototype 
PrincipalSearcher searcher = new PrincipalSearcher(prototype); 

// define a list of strings to hold the group names   
List<string> groupNames = new List<string>(); 

// iterate over the result of the .FindAll() call 
foreach(var gp in searcher.FindAll()) 
{ 
    // cast result to GroupPrincipal 
    GroupPrincipal group = gp as GroupPrincipal; 

    // if everything - grab the group's name and put it into the list 
    if(group != null) 
    { 
     groupNames.Add(group.Name); 
    } 
} 

是否能滿足您的需求?

有關System.DirectoryServices.AccountManagement命名空間的詳細信息,請閱讀MSDN雜誌中的Managing Directory Security Principals in the .NET Framework 3.5文章。

+0

謝謝馬克,我還沒有嘗試你的代碼,但無論如何,我會張貼我爲那些對這個話題感興趣的人做的解決方案。非常感謝。 – 2010-07-02 18:11:53