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?
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"];
The correct way, I believe, would be to executeWTSQuerySessionInformation
, 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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.