Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With WMI: How can I get the name of the user account who's running my program?

Tags:

c#

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.

like image 827
backslash17 Avatar asked Mar 01 '23 10:03

backslash17


2 Answers

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.

like image 120
adrianbanks Avatar answered Apr 26 '23 21:04

adrianbanks


You don't necessarily need to use WMI. Check out WindowsIdentity.

var identity = WindowsIdentity.GetCurrent();
var username = identity.Name;
like image 31
user7116 Avatar answered Apr 26 '23 20:04

user7116