Windows 2000 Server 引入的 Active Directory (AD) 採用可擴充儲存引擎 (ESS),支援百萬級物件、域樹與森林架構。在 .NET 中,System.DirectoryServices 命名空間提供豐富封裝類別,讓 AD 操作變得簡單直觀。本文以主控台應用程式為例,示範查詢組織單位 (OU)、群組與使用者的基礎操作流程。
System.DirectoryServices.dllusing System.DirectoryServices;| 類別 | 用途 |
|---|---|
DirectoryEntry | 代表 AD 中的節點(根目錄、OU、使用者等),建構子傳入 LDAP 路徑 |
DirectorySearcher | 執行查詢,設定 Filter 條件,呼叫 FindAll() 或 FindOne() |
SearchResult | 查詢結果項目,透過 GetDirectoryEntry() 取得底層節點屬性 |
(objectClass=organizationalUnit) // 所有 OU
(objectClass=group) // 所有群組
(objectClass=user) // 所有使用者
(&(objectClass=user)(cn=admin*)) // 組合條件:使用者且 CN 以 admin 開頭
public static void GetAllOU() {
DirectoryEntry entry = new DirectoryEntry("LDAP://szcs"); // szcs 為域名
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(objectClass=organizationalUnit)";
foreach (SearchResult result in searcher.FindAll()) {
DirectoryEntry ou = result.GetDirectoryEntry();
Console.WriteLine($"OU Name: {ou.Name}");
// 可進一步讀取屬性:ou.Properties["description"].Value 等
}
}
LDAP://<域名/伺服器>,亦可指定 OU 完整路徑如 LDAP://OU=Sales,DC=corp,DC=com& (AND)、| (OR)、! (NOT)、* (萬用字元)FindAll() 遞歸搜尋整棵樹,回傳 SearchResultCollectionDirectoryEntry,讀取 Name、Path、自訂屬性等DirectoryEntry 後操作 Properties 集合,呼叫 CommitChanges()new DirectoryEntry(path, username, password, AuthenticationTypes.Secure)DirectorySearcher.PageSize 分頁、PropertyNamesOnly 僅取屬性名稱LDAP://GC://forest.root 並設定 SearchScope.SubtreeSizeLimit、啟用分頁