tags:

views:

131

answers:

4

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#?

A: 

Altough I don't understand if you want to get the user name, who is logged on the system or the user name under which the console is running - maybe you could try using System.Environment.UserName - MSDN claims that it shows the logged on user name.

bernhardrusch
I want the user name who is logged on to the system. System.Environment.UserName returns only the username under which the program is running.
Santhosh
+3  A: 

I think you'd have to go down a P/Invoke route. You need to find out which WindowStation your process is running within, and then determine the owner of that WindowStation. I don't think that there's a .NET api for determining these things.

Win32 APIs that you'd need to look at, are probably GetProcessWindowStation and GetUserObjectSecurity to find the owner.

Damien_The_Unbeliever
This is wrong. The window station's security descriptor has nothing to do with the user who logged on. Any relationship is coincidental and has to do with the fact that the user needs to have access to the window station.
wj32
+1  A: 

You want the user name of your session. You can find out your session ID by calling ProcessIdToSessionId. Then use WTSQuerySessionInformation to find out the user name.

wj32