Windows 服务:用户登录时获取用户名 [英] Windows service: Get username when user log on

查看:53
本文介绍了Windows 服务:用户登录时获取用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Windows 服务应该保存用户的名称,此时登录/注销.以下代码适用于我,但没有保存用户名:

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");
        }
    }

foreach 循环给了我一个错误:

edit: The foreach loop gives me an error:

消息:访问被拒绝.(来自 HRESULT 的异常:0x80070005(E_ACCESSDENIED)) 类型:System.UnauthorizedAccessException

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.

推荐答案

我终于找到了解决方案.在 windows 服务方法中,提供了会话 ID.因此,使用此会话 ID,我们可以执行 powershell 命令quser"并获取当前用户,该用户在服务器上登录/注销.在这里看到:如何获取当前窗口使用 .NET 的多用户环境中 Windows 服务的用户名

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:

private string GetUsername(int sessionID)
        {
            try
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript("Quser");
                pipeline.Commands.Add("Out-String");

                Collection<PSObject> results = pipeline.Invoke();

                runspace.Close();

                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                foreach (string User in stringBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1))
                {
                    string[] UserAttributes = User.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    if (UserAttributes.Length == 6)
                    {
                        if (int.Parse(UserAttributes[1].Trim()) == sessionID)
                        {
                            return UserAttributes[0].Replace(">", string.Empty).Trim();
                        }
                    }
                    else
                    {
                        if (int.Parse(UserAttributes[2].Trim()) == sessionID)
                        {
                            return UserAttributes[0].Replace(">", string.Empty).Trim();
                        }
                    }
                }

            }
            catch (Exception exp)
            {
                // Error handling
            }

            return "Undefined";
        } 

这是windows服务功能:

And this is the windows service function:

protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            try
            {
                switch (changeDescription.Reason)
                {
                    case SessionChangeReason.SessionLogon:
                        string user = GetUsername(changeDescription.SessionId);

                        WriteLog("Logon - Program continue" + Environment.NewLine + 
                            "User: " + user + Environment.NewLine + "Sessionid: " + changeDescription.SessionId);

                        //.....

这篇关于Windows 服务:用户登录时获取用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆