2014-07-04 41 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

相關問題