如果你在.NET 3.5及以上,你應該看看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空間。在這裏閱讀全部內容:
基本上,你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
// 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
}
}
的新的S.DS.AM可以很方便地與AD中的用戶和羣組玩轉:
計算機帳戶將顯示爲ComputerPrincipal
(源自Principal
) - 因此您可以輕鬆地將用戶和計算機帳戶分開。
如果您不能或不想移動到S.DS.AM--您還可以通過在您的LDAP過濾器中使用objectCategory
而不是objectClass來分開用戶和計算機。無論如何,objectCategory
是有益的,因爲它被索引,而不是多值 - 所以查詢性能會好很多。
對於真實的用戶,請使用objectCategory = Person
,而對於計算機,請在您的LDAP過濾器中使用objectCategory = Computer
。