2014-07-04 34 views
0

我正在使用下面的代码获取Active Directory中所有用户的电子邮件。但是,该代码还会返回已在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。

回答

0

您可以使用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的“查询范例”。

+0

我现在就试试 – Nate

相关问题