How do I get the current username in .NET using C#?

Try the property: Environment.UserName.


If you are in a network of users, then the username will be different:

Environment.UserName
- Will Display format : 'Username'

rather than

System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'

Choose the format you want.


Option A)

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
  • Returns: NetworkName\Username
  • Gets the user's Windows logon name.
  • Details: https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity

Option B)

string userName = Environment.UserName
  • Returns: Username
  • Gets the user name of the person who is associated with the current thread.
  • Details: https://docs.microsoft.com/en-us/dotnet/api/system.environment.username

Tags:

C#

.Net