2011-12-22 69 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