We can easily find current username in C# by using either by Environment class or WindowsIdentity.
1 | Environment.UserName |
– Return username without domain part
1 | System.Security.Principal.WindowsIdentity.GetCurrent().Name |
– Return username with domain part : ‘DomainNameUsername’
You need to add reference to System.Security.Principal to use WindowsIdentity class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System; using System.Security.Principal; namespace GetUserInfo { class Program { static void Main( string [] args) { Console.WriteLine( "UserName: " + Environment.UserName); Console.WriteLine( "IdentityName: " + WindowsIdentity.GetCurrent().Name); } } } |
Advertisement