Saturday, September 8, 2007

Detecting is current user an Administrator

In some cases in your windows application you may want to know is the current user a member of Aministrators group or not?
To detect this you can get an object of WindowsIdentity like this:

WindowsIdentity identity = WindowsIdentity.GetCurrent();

Then create an instance of WindowsPrincipan by :

WindowsPrincipal principal = new WindowsPrincipal(identity);

and finally check it by using IsInRole() method like this:

string role = "BUILTIN\\Administrators";
bool IsAdmin = principal.IsInRole(role));

then you can use the IsAdmin variable to determine whether the current user is an Admin or not.


Anonymous said...

you can also do this:

bool IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

Anonymous said...

in Vista IsAdmin always is false.
any idea?

Jared Hodges said...

In Vista they have to be elevated to administrator. See for details.

Anonymous said...

thank you jared, this will help me.

Anonymous said...

I tried this with domain user that's added to local administrators group but it still cannot return true.

Any idea?