How to get Windows user name using different methods?

Andy picture Andy · Jul 4, 2010 · Viewed 27.7k times · Source

In .NET, there appears to be several ways to get the current Windows user name. Three of which are:

string name = WindowsIdentity.GetCurrent().Name;

or

string name = Thread.CurrentPrincipal.Identity.Name;

or

string name = Environment.UserName;

What's the difference, and why choose one method over the other? Are there any other ways?

Answer

sisve picture sisve · Jul 4, 2010

Environment.UserName calls GetUserName within advapi32.dll. This means that if you're impersonating another user, this property will reflect that.

Thread.CurrentPrincipal has a setter and can be changed programmatically. (This is not impersonation btw.)

WindowsIdentity is your current windows identity, if any. It will not necessarily reflect the user, think ASP.NET with FormsAuthentication. Then the WindowsIdentity will be the NT-service, but the FormsIdentity will be the logged in user. There's also a PassportIdentity, and you can build your own stuff to complicate things further.