I have a service that I had to log on to the local admin to install. The pupose of this service to log when a user is logging in or out to record their username. I finally found a bit of WMI code that I thought would work, but it is still returning Administrator. Why isn’t this working?
var query = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");
var explorerProcesses = new ManagementObjectSearcher(query).Get();
foreach (ManagementObject mo in explorerProcesses)
{
string[] ownerInfo = new string[2];
mo.InvokeMethod("GetOwner", (object[])ownerInfo);
userName = String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
}
Console.WriteLine(userName);
Console.ReadLine();
To clarify my question I’m tring to get the currently logged on user but its giving me back Adminstrator the account I used to install the service.
You should use Service Control Manager Notifications for this. You can configure your service to receive notification events when a user logs on and / or logs off. This allows a service to do interactive user impersonation if the service requires it, but it should give you the info you need for your logging.
Check out the section “Using Service Control Manager (SCM) Notifications” here http://technet.microsoft.com/en-us/library/cc721961(WS.10).aspx
edit
In your Service class override the OnSessionChange event handler to check for logon and logoff events.
edit2:
edit3: