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:
I know this thread is old, but if anyone need to know how it works:
Add a reference to
System.Management
Put
using System.Management;
at the top of your fileCreate this private variable in your class:
Create this method in your service:
Now you got the username in
user
. If the computer is in a domain it looks like thisdomain\username
Try to change the Account() method inserting the sessionId parameter and passing the changeDescription.SessionId to the method WTSQueryUserToken
p.s.: Run your service with LocalSystem account
Here's my code (all of them residing inside a class; in my case, the class inheriting
ServiceBase
).With the above code in your class, you can simply get the username in the method you're overriding like this: