如果您使用的是.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)
{
// update the properties you need to
user.DisplayName = "Joe Blow";
user.Description = "Some description";
// save back your changes
user.Save();
}
的新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!
如果你需要搜索一大堆的用戶,可以使用PrincipalSearcher
和「查詢通過例如」主要做你的搜索:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) of "Bruce"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
UserPrincipal user = found as UserPrincipal;
if(user != null)
{
// update the properties you need to
user.DisplayName = "Joe Blow";
user.Description = "Some description";
// save back your changes
user.Save();
}
}
您可以指定任何屬性UserPrincipal
並將它們用作您的PrincipalSearcher
的「查詢範例」。
感謝您的回答。我聽說過AccountManagement,有人告訴我,你可以訪問哪些屬性是非常有限的。我在擴展屬性中存儲了大量數據,我仍然可以使用S.DS.AM? – elwis 2011-12-22 09:55:46
@elwis:閱讀我已鏈接的文章!你可以擴展'UserPrincipal'類來滿足你的需求,是的,你完全可以使用S.DS.AM來完成你的任務!如果一切都失敗了,你總是可以調用'.GetUnderlyingObject()',並且使用屬於那個'UserPrincipal'的'DirectoryEntry'並且處理擴展屬性的更新。 – 2011-12-22 09:56:38
HAV來評論。我無法使用該解決方案,但我仍然閱讀您的文章,這似乎是一個很好的解決方案。希望下次,謝謝你的鏈接 – elwis 2012-01-04 06:44:54