Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current Windows user — not current user running process

How do I get the current logged in Windows user? my problem: i'm running a process with administrator privileges and all these:

Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
Console.WriteLine(Environment.UserName);
Console.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().User); //GUID
Console.WriteLine(Environment.GetEnvironmentVariable("USERNAME"));

...tries give me back the current user who runs the process, in my case Administrator - but i'd like to have the current user who is logged in.

Any ideas or suggestions?

like image 444
Markus Avatar asked Aug 24 '26 11:08

Markus


2 Answers

I found this method a long time ago. I am using the WMI query

ManagementObjectSearcher searcher = 
     new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");

ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
like image 98
Bundeskanzler. Avatar answered Aug 27 '26 01:08

Bundeskanzler.


The correct way, I believe, would be to execute WTSQuerySessionInformation, something along the lines of:

WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,WTS_CURRENT_SESSION,
                           WTSUserName,buffer, out byteCount);

PInvoke page for this function.


Tangentially related, but may be of interest - How can I launch an unelevated process from my elevated process and vice versa?

like image 20
Damien_The_Unbeliever Avatar answered Aug 27 '26 02:08

Damien_The_Unbeliever