Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the first name and last name of the logged in Windows user?

How I can get my first name last name with c# in my system (logging in windows with Active Directory username and pass)?

Is it possible to do that without going to the AD?

like image 868
Data-Base Avatar asked Aug 12 '10 20:08

Data-Base


1 Answers

If you're using .Net 3.0 or higher, there's a lovely library that makes this practically write itself. System.DirectoryServices.AccountManagement has a UserPrincipal object that gets exactly what you are looking for and you don't have to mess with LDAP or drop to system calls to do it. Here's all it'd take:

Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal; // or, if you're in Asp.Net with windows authentication you can use: // WindowsPrincipal principal = (WindowsPrincipal)User; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) {     UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);     return up.DisplayName;     // or return up.GivenName + " " + up.Surname; } 

Note: you don't actually need the principal if you already have the username, but if you're running under the users context, it's just as easy to pull it from there.

like image 153
Jacob Proffitt Avatar answered Oct 04 '22 20:10

Jacob Proffitt