2011-12-22 41 views
1

我正在編寫一個小應用程序,它使用數據庫表中的信息更新我的AD,但無法找到最佳實踐的示例。使用DirectoryService更新用戶

據我瞭解,我需要:

  • 創建一個DirectorySearcher與過濾器objectClass=user,並搜索給定的CN
  • 如果找到了,我需要使用result.getDirectoryEntry得到一個手柄實際的對象,
  • 更新都與一個人的從數據庫中,然後將值以我entryobject提交更改

是這樣它或我完全丟失,任何提示或示例都歡迎

回答

1

如果您使用的是.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的「查詢範例」。

+0

感謝您的回答。我聽說過AccountManagement,有人告訴我,你可以訪問哪些屬性是非常有限的。我在擴展屬性中存儲了大量數據,我仍然可以使用S.DS.AM? – elwis 2011-12-22 09:55:46

+0

@elwis:閱讀我已鏈接的文章!你可以擴展'UserPrincipal'類來滿足你的需求,是的,你完全可以使用S.DS.AM來完成你的任務!如果一切都失敗了,你總是可以調用'.GetUnderlyingObject()',並且使用屬於那個'UserPrincipal'的'DirectoryEntry'並且處理擴展屬性的更新。 – 2011-12-22 09:56:38

+0

HAV來評論。我無法使用該解決方案,但我仍然閱讀您的文章,這似乎是一個很好的解決方案。希望下次,謝謝你的鏈接 – elwis 2012-01-04 06:44:54