使用 WMI:如何获取运行我的程序的用户帐户的名称?
我需要将对我的应用程序的访问限制为只有一个特定的用户帐户。 我在 WMI 下找到了类来查找用户帐户,但我不知道如何识别哪个正在运行我的应用程序。
I need to restrict access to my application to only one specific user account. I have found classes under WMI to find users accounts, but I don´t know how to recognize which one is running my app.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有比使用 WMI 更简单的方法来获取当前用户名。
WindowsIdentity.GetCurrent()。Name 将获取当前 Windows 用户的名称。
Environment.Username 将为您提供当前登录的用户。
两者之间的区别在于
WindowsIdentity.GetCurrent().Name
还将包含域名和用户名(即MYDOMAIN\adrian
而不是阿德里安
)。 如果您需要Environment
中的域名,可以使用Environment.UserDomainName。编辑
如果您确实想使用 WMI 执行此操作,可以执行以下操作:
不幸的是,
ManagementObjectCollection
上没有索引器属性,因此您必须枚举它才能获取第一个 (并且只有)结果。There are simpler ways to get the current username than using WMI.
WindowsIdentity.GetCurrent().Name will get you the name of the current Windows user.
Environment.Username will get you the name of the currently logged on user.
The difference between these two is that
WindowsIdentity.GetCurrent().Name
will also include the domain name as well as the username (ie.MYDOMAIN\adrian
instead ofadrian
). If you need the domain name fromEnvironment
, you can use Environment.UserDomainName.EDIT
If you really want to do it using WMI, you can do this:
Unfortunately, there is no indexer property on
ManagementObjectCollection
so you have to enumerate it to get the first (and only) result.您不一定需要使用 WMI。 请查看 WindowsIdentity。
You don't necessarily need to use WMI. Check out WindowsIdentity.
最简单的方法是通过环境类:
还有多种方法可以限制特定用户(尽管检查角色更常见)。
除了明显的之外,
您还可以在整个类或特定方法上使用以下属性:
这对于低级、可重用的方法来说可能更可靠。
请注意,您可以同时使用两者,使用 if() 作为程序正常流程的一部分检查用户,并使用属性作为关键方法的保护措施。
The simplest approach is through the Environment class:
There also are several ways to restrict to a certain user (although checking for a role is more common).
Apart from the obvious
You can also use the following attribute on an entire class or specific methods:
Which could be a bit more reliable for low-level, reusable methods.
Note that you could use both, checking for a user with if() as part of the normal flow of the program and the attribute as a safeguard on critical methods.