38

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?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Andy
  • 5,188
  • 10
  • 42
  • 59

4 Answers4

32

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.

sisve
  • 19,501
  • 3
  • 53
  • 95
  • Does "impersonation" mean if you run something via "Run as..."? – Andy Jul 04 '10 at 19:21
  • @Andy, I havnt tried that. But the WindowsIdentity class has an Impersonate() method, and I am pretty sure that _it_ will do impersonation. ;) – sisve Jul 04 '10 at 19:23
1

You asked for alternative ways.

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

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
0

The three methods are described as follow:

HttpContext = HttpContext.Current.User, which returns an IPrincipal object that contains security information for the current Web request. This is the authenticated Web client.

WindowsIdentity = WindowsIdentity.GetCurrent(), which returns the identity of the security context of the currently executing Win32 thread.

Thread = Thread.CurrentPrincipal which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

And they change in result depending on your IIS configuration as explained in this article: http://msdn.microsoft.com/en-us/library/aa302377.aspx

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36
Maurizio In denmark
  • 4,226
  • 2
  • 30
  • 64
0

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
  • 18,794
  • 5
  • 57
  • 67