需要帮助将DirectoryServices代码转换为PrincipalContext

时间:2016-04-01 21:19:19

标签: c#-4.0 directoryservices principalcontext

DirectorySearcher deSearch;SearchResultCollection result;
deSearch.SearchRoot = baseResult.GetDirectoryEntry();// I know this one can be done like - PrincipalContext pContext = new PrincipalContext(ContextType.Domain, deSearch.SearchRoot.Path);
deSearch.Filter = "(&(&(objectClass=user)(objectCategory=person))(name=" + name + "))"; //???? **Not sure how to apply the filter in Principal Context**
results = deSearch.FindAll();

请帮我在principlecontext中应用过滤器

1 个答案:

答案 0 :(得分:0)

您可以使用PrincipalSearcher搜索特定用户。

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{ 
   UserPrincipal searchUser = new UserPrincipal(ctx);
   searchUser.GivenName = "Name";

   PrincipalSearcher srch = new PrincipalSearcher(searchUser);
   foreach(var found in srch.FindAll())
   {
     //found will contain the info   
   } 
}

您也可以使用UserPrincipal

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, "DN"))
   if (user != null)
   {
      //user contains info
   }
}

如果您想按IdentityType等搜索,可以定义不同的samAccountName