Assume that there is an organizational unit in AD and the following information is given:
AD: ms.com
AD administrator: administrator
AD administrator password: pass @ word1
Organization unit name: XX Company Limited (ignore the number of organizational units nested under it, usually Departments)
Now you need to obtain all the user information under the organization, such as the account, name, email, and organization fields. The specific implementation is shown in the sample code: Private const string domainName = "ms.com ";
Private const string adAdmin = "administrator ";
Private const string password = "pass @ word1 ";
Private const string ouName = "XX Ltd ";
Private DataTable GetADUsers ()
{
DataTable dt = new DataTable ();
Dt. Columns. Add ("sAMAccountName"); // account
Dt. Columns. Add ("Name"); // Name
Dt. Columns. Add ("mail"); // email address
Dt. Columns. Add ("OU"); // user organization
DirectoryEntry adRoot = new DirectoryEntry ("LDAP: //" + domainName, adAdmin, password, AuthenticationTypes. Secure );
DirectoryEntry ou = adRoot. Children. Find ("OU =" + ouName );
DirectorySearcher mySearcher = new DirectorySearcher (ou );
MySearcher. Filter = ("(objectClass = user)"); // user indicates the user and group indicates the group
Foreach (System. DirectoryServices. SearchResult resEnt in mySearcher. FindAll ())
{
DataRow dr = dt. NewRow ();
Dr ["sAMAccountName"] = string. Empty;
Dr ["Name"] = string. Empty;
Dr ["mail"] = string. Empty;
Dr ["OU"] = string. Empty;
DirectoryEntry user = resEnt. GetDirectoryEntry ();
If (user. Properties. Contains ("sAMAccountName "))
{
Dr ["sAMAccountName"] = user. Properties ["sAMAccountName"] [0]. ToString ();
}
If (user. Properties. Contains ("Name "))
{
Dr ["Name"] = user. Properties ["Name"] [0]. ToString ();
}
If (user. Properties. Contains ("mail "))
{
Dr ["mail"] = user. Properties ["mail"] [0]. ToString ();
}
If (user. Parent. Name! = String. Empty & user. Parent. Name. IndexOf ('=')>-1)
{
// Obtain the organizational unit of the user
Dr ["OU"] = user. Parent. Name. Split ('=') [1];
}
Dt. Rows. Add (dr );
}
Return dt;
}
}
If you want to know which fields are included in the user information, you can use foreach to see DirectoryEntry user = resEnt. GetDirectoryEntry ();
Foreach (string property in user. Properties. PropertyNames)
{
Console. WriteLine ("field name:" + property );
}