Get currently logged in user c#

We can easily find current username in C# by using either by Environment class or WindowsIdentity.

 

Environment.UserName

– Return username without domain part

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.

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

Leave a Comment