Brian
asked on
C# code to grab AD user info
The C# code below will grab user info, but I don't see a way to grab the first name or last name (which I believe is givenName and Surname). I can grab things like the Name (which is username), SamAccountName, UserPrincipalName, etc., but I can figure out how to get the first or last name of the user. Can someone help? Thanks!
private void button1_Click_1(object sender, EventArgs e)
{
string userName;
string strUPN;
bool isValid;
List<string> allUsers = new List<string>();
// define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=MyDept,OU=MyUsers,dc=MyDomain,dc=local");
// search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
// "found" is of type "Principal"
userName = found.Name;
strUPN = found.SamAccountName;
allUsers.Add(userName + " " + strUPN);
}
MessageBox.Show(allUsers[499]);
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi Brian,
Please check two things, 1. In AD the last name is really populated and put a debugger point on
What do you see in the debugger?
Regards,
Chinmay.
Please check two things, 1. In AD the last name is really populated and put a debugger point on
entry.Properties["surName"].Value)
What do you see in the debugger?
Regards,
Chinmay.
ASKER
Turns out it is "sn" instead of "surName". Thanks for all your help, Chinmay!
ASKER
Thanks for the fast response and the nice, concise code!
Glad I could help 🙂
ASKER
And it did return the first name, but not the last name. It did not give an error, but did not return the surname. Maybe the syntax is incorrect for surName?