Problem
In.NET, how can I get the current username using C#?
Asked by Yves
Solution #1
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Answered by juan
Solution #2
If you’re part of a user network, your username will be different:
Environment.UserName
- Will Display format : 'Username'
rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
Select the desired format.
Answered by Israel Margulies
Solution #3
Try the Environment.UserName property.
Answered by JaredPar
Solution #4
The Environment documentation. UserName appears to be a little ambiguous:
Environment.UserName Property
On the same page, it is written:
AND
When you use RunAs to test Environment.UserName, it will return the name of the RunAs user account, not the person who first signed on to Windows.
Answered by Kobus
Solution #5
I completely agree with the other responses, however I’d like to add one more technique that says
String UserName = Request.LogonUserIdentity.Name;
The username returned by the aforesaid procedure was in the format DomainNameUserName. EUROPEUserName, for example.
What is the difference between:
String UserName = Environment.UserName;
Which appears in the following format: UserName
And finally:
String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
NT AUTHORITYIUSR (when running the application on an IIS server) and DomainNameUserName were returned (while running the application on a local server).
Answered by Shivam657
Post is based on https://stackoverflow.com/questions/1240373/how-do-i-get-the-current-username-in-net-using-c