Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Windows user name using different methods?

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?

like image 798
Andy Avatar asked Jul 04 '10 14:07

Andy


People also ask

How do I find my username using CMD?

In the box, type cmd and press Enter. The command prompt window will appear. Type whoami and press Enter. Your current user name will be displayed.

How do I find my computer's username?

Click Start, right-click Computer, and then click Properties. The computer name appears under Computer name, domain, and workgroup settings.

How do I find my username on Windows 10?

Step 1: – Search netplwiz in start menu search box of windows 10. Step 2: – Now, from the list of users, click on the user you want to know the username for.


2 Answers

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.

like image 89
sisve Avatar answered Sep 20 '22 21:09

sisve


You asked for alternative ways.

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

like image 39
Andreas Rejbrand Avatar answered Sep 21 '22 21:09

Andreas Rejbrand