Sunday, 24 January 2016

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 : 'DomainName\Username'

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);
        }
    }
}

Advertisements
Advertisements

No comments:

Post a Comment