使用DirectoryService更新用户

时间:2011-12-22 09:24:03

标签: active-directory directoryservices

我正在编写一个小应用程序,它使用数据库表中的信息更新我的AD,但无法找到最佳实践的示例。

据我了解,我需要:

  • 使用过滤器DirectorySearcher创建objectClass=user并搜索给定的cn
  • 如果找到,我需要使用result.getDirectoryEntry来获取实际对象的句柄,
  • 使用数据库中的一个更新所有值entryobject,然后提交更改

是它还是我完全失去了,欢迎任何提示或例子

1 个答案:

答案 0 :(得分: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的“按示例查询”。