[英]With WMI: How can I get the name of the user account who's running my program?
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.
我在 WMI 下找到了一些类来查找用户帐户,但我不知道如何识别哪个正在运行我的应用程序。
There are simpler ways to get the current username than using WMI.有比使用 WMI 更简单的方法来获取当前用户名。
WindowsIdentity.GetCurrent() . WindowsIdentity.GetCurrent() 。 Name will get you the name of the current Windows user.
Name将为您提供当前 Windows 用户的名称。
Environment.Username will get you the name of the currently logged on user. Environment.Username将为您提供当前登录用户的名称。
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 of adrian
).这两者之间的区别在于
WindowsIdentity.GetCurrent().Name
还将包括域名和用户名(即MYDOMAIN\\adrian
而不是adrian
)。 If you need the domain name from Environment
, you can use Environment.UserDomainName .如果您需要来自
Environment
的域名,您可以使用Environment.UserDomainName 。
EDIT编辑
If you really want to do it using WMI, you can do this:如果你真的想用 WMI 来做,你可以这样做:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string) collection.Cast<ManagementBaseObject>().First()["UserName"];
Unfortunately, there is no indexer property on ManagementObjectCollection
so you have to enumerate it to get the first (and only) result.不幸的是,
ManagementObjectCollection
上没有索引器属性,因此您必须枚举它以获得第一个(也是唯一的)结果。
You don't necessarily need to use WMI.您不一定需要使用 WMI。 Check out WindowsIdentity .
查看WindowsIdentity 。
var identity = WindowsIdentity.GetCurrent();
var username = identity.Name;
The simplest approach is through the Environment class:最简单的方法是通过 Environment 类:
string user = Environment.UserDomainName + "\\" + Environment.UserName;
There also are several ways to restrict to a certain user (although checking for a role is more common).还有几种方法可以限制特定用户(尽管检查角色更为常见)。
Apart from the obvious除了显而易见的
if (userName == "domain\\john")
{ }
You can also use the following attribute on an entire class or specific methods:您还可以在整个类或特定方法上使用以下属性:
[PrincipalPermission(SecurityAction.Demand, Name = "domain\\john",
Authenticated = true)]
void MyMethod()
{
}
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.请注意,您可以同时使用两者,使用 if() 作为程序正常流程的一部分检查用户,并将属性作为关键方法的保护措施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.