From WMI: How can I get the name of the user account that runs my program?

I need to restrict access to my application to only one specific user account. I found classes under WMI to find user accounts, but I don’t know how to recognize how the application works.

Thanks in advance for your answers.

+4
source share
3 answers

There are easier ways to get the current username than using WMI.

WindowsIdentity.GetCurrent () . Name you will get the name of the current Windows user.

Environment.Username will give you the name of the current user.

The difference between the two is that WindowsIdentity.GetCurrent().Name will also include the domain name as well as the username (i.e. MYDOMAIN\adrian instead of adrian ). If you need a domain name from Environment , you can use Environment.UserDomainName .

EDIT

If you really want to do this 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 the ManagementObjectCollection , so you need to list it to get the first (and only) result.

+6
source

You do not have to use WMI. Check out WindowsIdentity .

 var identity = WindowsIdentity.GetCurrent(); var username = identity.Name; 
+1
source

The easiest approach is through the environment class:

 string user = Environment.UserDomainName + "\\" + Environment.UserName; 

There are also several ways to restrict access to a specific user (although role checking is more common).

Beyond the obvious

 if (userName == "domain\\john") { } 

You can also use the following attribute for the entire class or specific methods:

 [PrincipalPermission(SecurityAction.Demand, Name = "domain\\john", Authenticated = true)] void MyMethod() { } 

Which may be a little more reliable for low-level reusable methods.

Note that you can use both, checking for the user that if () as part of the normal program flow and attribute as protection for critical methods.

+1
source

All Articles