views:

60

answers:

3

In .NET there appears to 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?

A: 

I believe the property was put in several places so that it would be easier for the programmer to find. There's only one logged in user, and only one respective name.

Pavel Radzivilovsky
@Pavel : So by implication, all these methods are interchangable?
Andy
I believe yes. I'd expect no subtle differences here.
Pavel Radzivilovsky
A: 

You asked for alternative ways.

Of course, you can always use the native Windows API: GetUserName.

Andreas Rejbrand
+3  A: 

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.

Simon Svensson
@Simon : Does "impersonation" mean if you run something via "Run as..."?
Andy
@Andy, I havnt tried that. But the WindowsIdentity class has an Impersonate() method, and I am pretty sure that _it_ will do impersonation. ;)
Simon Svensson