How do I get the AD Display Name of the currently

2019-01-14 08:48发布

问题:

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

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?

回答1:

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

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

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.



回答2:

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.