The following code will return the name and email address of all users in a specified Active Directory domain that have not been disabled.
The only tricky part is setting up the LDAP query to only return users that have not been disabled. This is accomplished by setting this bitwise filter
"(!(userAccountControl:1.2.840.113556.1.4.803:=2))"
In this line we are saying look at the "UserAccountControl" attribute in Active Directory and if it is not equal to "2" then return true.
The 1.2.840.113556.1.4.803 tells it to use the LDAP_MATCHING_RULE_BIT_AND operator to make the comparison.
There is a little more on using the bitwise operators in ActiveDirectory here .
public static DataTable GetListOfActiveUsers(string domainName)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=" + domainName + ",DC=com");
DirectorySearcher search = new DirectorySearcher(entry);
string query = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(&(mail=*)))";
search.Filter = query;
search.PropertiesToLoad.Add("name");
search.PropertiesToLoad.Add("mail");
SearchResultCollection mySearchResultColl = search.FindAll();
DataTable results = new DataTable();
results.Columns.Add("name");
results.Columns.Add("mail");
foreach (SearchResult sr in mySearchResultColl)
{
DataRow dr = results.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
dr["name"] = de.Properties["Name"].Value;
dr["mail"] = de.Properties["mail"].Value;
results.Rows.Add(dr);
de.Close();
}
return results;
}
}
No comments:
Post a Comment