my windows service should save the name of the user, which logon/logoff at the moment. The following code works for me but didn't save the username:
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
try
{
string user = "";
foreach (ManagementObject currentObject in _wmiComputerSystem.GetInstances())
{
user += currentObject.Properties["UserName"].Value.ToString().Trim();
}
switch (changeDescription.Reason)
{
case SessionChangeReason.SessionLogon:
WriteLog(Constants.LogType.CONTINUE, "Logon - Program continues: " + user);
OnContinue();
break;
case SessionChangeReason.SessionLogoff:
WriteLog(Constants.LogType.PAUSE, "Logoff - Program is paused: " + user);
OnPause();
break;
}
base.OnSessionChange(changeDescription);
}
catch (Exception exp)
{
WriteLog(Constants.LogType.ERROR, "Error");
}
}
edit: The foreach loop gives me an error:
Message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) Type: System.UnauthorizedAccessException
But in my opinion, this code is not the solution, because it saves all users, which are logged onto the server.
You could try:
another option, see: Getting logged-on username from a service
Finally I got a solution. In the windows service method, there is the session id provided. So with this session id we can execute a powershell command 'quser' and get the current user, who login/logoff on the server. Seen here: How to get current windows username from windows service in multiuser environment using .NET
So this is the function, which we need to create:
And this is the windows service function:
I ran into a similar problem while building a Windows Service. Just like you, I had the Session ID and needed to get the corresponding username. After several unsuccessful solution hereon SO, I ran into this particular answer and it inspired my solution:
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 by calling