In.NET, how can I get the current username using C#?
Asked by Yves
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Answered by juan
If you’re part of a user network, your username will be different:
Environment.UserName - Will Display format : 'Username'
System.Security.Principal.WindowsIdentity.GetCurrent().Name - Will Display format : 'NetworkName\Username'
Select the desired format.
Answered by Israel Margulies
Try the Environment.UserName property.
Answered by JaredPar
The Environment documentation. UserName appears to be a little ambiguous:
On the same page, it is written:
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
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
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