tags:

views:

332

answers:

2

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 wich one is running my app.

Thanks in advance for your anserws.

+1  A: 

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

var identity = WindowsIdentity.GetCurrent();
var username = identity.Name;
sixlettervariables
+4  A: 

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.

adrianbanks
Thanks, is much easier and I will use it, but ¿is there a way to do it with WMI?
backslash17
Sorry for the inverted question mark!
backslash17