【问题标题】:How do you retrieve only active users (that haven't been disabled) from Active Directory如何从 Active Directory 中仅检索活动用户(尚未禁用)
【发布时间】:2014-07-04 11:39:48
【问题描述】:

我正在使用下面的代码来获取 Active Directory 中所有用户的电子邮件。但是,该代码还会返回已在 Active Directory 中禁用的用户。

如何过滤结果以仅返回拥有活动帐户的用户?

DirectoryEntry entry = new DirectoryEntry("LDAP://MyDomain");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(objectClass=user)";

foreach (SearchResult sResultSet in dSearch.FindAll())
{
    if (sResultSet.Properties["mail"].Count > 0)
        Response.Write(sResultSet.Properties["mail"][0].ToString() + "<br/>");
}

我认为 Active Directory 中可能有一个属性来定义帐户是否被禁用,我可以使用此属性来过滤结果。

我正在使用 C# .NET。

【问题讨论】:

    标签: c# asp.net email active-directory


    【解决方案1】:

    您可以使用PrincipalSearcher 和“示例查询”主体进行搜索:

    // create your domain context
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
       // define a "query-by-example" principal - here, we search for enabled UserPrincipal 
       UserPrincipal qbeUser = new UserPrincipal(ctx);
       qbeUser.Enabled = true;
    
       // create your principal searcher passing in the QBE principal    
       PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
    
       List<string> emails = new List<string>();
    
       // find all matches
       foreach(var found in srch.FindAll())
       {
           UserPrincipal foundUser = found as UserPrincipal;
           emails.Add(foundUser.EmailAddress);
       }
    }
    

    如果您还没有 - 一定要阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement 命名空间。

    您可以在UserPrincipal 上指定任何属性并将其用作PrincipalSearcher 的“示例查询”。

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2018-11-29
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多