Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

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]);
        }
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

Thanks Chinmay! I changed the last line to this...  allUsers.Add(givenName + " " + surName);
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?
Hi Brian,

Please check two things, 1. In AD the last name is really populated and put a debugger point on
entry.Properties["surName"].Value)

Open in new window


What do you see in the debugger?

Regards,
Chinmay.
Avatar of Brian

ASKER

Turns out it is "sn" instead of "surName". Thanks for all your help, Chinmay!
Avatar of Brian

ASKER

Thanks for the fast response and the nice, concise code!
Glad I could help 🙂