如何从 .NET 中的 Windows 服务获取当前登录的用户名? [英] How do I get the currently-logged username from a Windows service in .NET?

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

问题描述

我有一个需要当前登录的用户名的 Windows 服务.我尝试了 System.Environment.UserName、Windows 身份和 Windows 表单身份验证,但所有都以用户身份返回系统",因为我的服务以系统特权运行.有没有办法在不更改我的服务帐户类型的情况下获取当前登录的用户名?

I have a Windows service which need the currently logged username. I tried System.Environment.UserName, Windows identity and Windows form authentication, but all are returning "System" as the user as my service is running in system privileged. Is there a way to get the currently logged in username without changing my service account type?

推荐答案

这是一个 WMI查询以获取用户名:

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

您需要手动在 References 下添加 System.Management.

You will need to add System.Management under References manually.

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

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