Reputation: 350
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?
Upvotes: 3
Views: 2000
Reputation: 239764
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?
Upvotes: 2
Reputation: 90
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"];
Upvotes: 4