Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the logged on user name in C#

Tags:

c#

login

How do i get the current logged on user name in windows 7 (i.e the user who is physically logged on to the console in which the program that i am launching is running).

For example if i am logged on as "MainUser" and run my console application (that will display the logged on user name) as "SubUser", then the program only returns "SubUser" as the currently logged on user.

I used the following 2 techniques to get the user name. Both are not getting me the thing that i want.

System.Environment.GetEnvironmentVariable("USERNAME")
System.Security.Principal.WindowsIdentity.GetCurrent().User;

Note that however, this VBScript code returns the logged on user name irrespective of the user account from which this script is run:

strComputer = "." 
Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set compsys_arr = objWMIService.ExecQuery _ 
    ("Select * from Win32_ComputerSystem") 
For Each sys in compsys_arr
    Wscript.Echo "username: " & sys.UserName
Next

Any way it is possible in C#?

like image 224
Santhosh Avatar asked Oct 28 '10 06:10

Santhosh


1 Answers

I think just converting the WMI calls to c# works just fine for me.

            ConnectionOptions oConn = new ConnectionOptions();
            System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);


            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();

            foreach (ManagementObject oReturn in oReturnCollection) {
                Console.WriteLine(oReturn["UserName"].ToString().ToLower());
            }
like image 152
Santhosh Avatar answered Oct 07 '22 15:10

Santhosh