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.
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 of adrian
). If you need the domain name from Environment
, you can use Environment.UserDomainName.
EDIT
If you really want to do it using WMI, you can do this:
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.
You don't necessarily need to use WMI. Check out WindowsIdentity.
var identity = WindowsIdentity.GetCurrent();
var username = identity.Name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With