12

Consider the following properties as set up in Active Directory for a user:

enter image description here

In my winforms application I would like to show the Display Name of the user who is currently logged on and using the application. How would I go about retrieving this information?

Martin
  • 39,569
  • 20
  • 99
  • 130

2 Answers2

27

Since you're on .NET 4, you can use the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find currently logged in user
UserPrincipal user = UserPrincipal.Current;

string displayName = user.DisplayName;    

The new S.DS.AM makes it really easy to play around with users and groups in AD.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
11

After hours of searching for the simplest way I finally came across this

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;

I wanted to get it out there for more people like me.

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Lee
  • 346
  • 3
  • 9
  • This was exactly what I needed, for a powershell script. Excellent. – xan Oct 30 '13 at 16:35
  • Worked great. The only thing I cant get from this is the users manager? – Kieran Quinn Mar 20 '15 at 10:29
  • 2
    When I do this I get "cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal" error... – jroyce Oct 01 '18 at 21:55