69

Possible Duplicate:
Check if the current user is administrator

I need to test if the application (written in C#, running os Windows XP/Vista/7) is running as administrator (as in right-click .exe -> Run as Administrator, or Run as Administrator in the Compability tab under Properties).

I have googled and searched StackOverflow but i can not find a working solution.

My last attempt was this:

if ((new WindowsPrincipal(WindowsIdentity.GetCurrent()))
         .IsInRole(WindowsBuiltInRole.Administrator))
{
    ...
}
Community
  • 1
  • 1
EClaesson
  • 1,568
  • 2
  • 15
  • 26

1 Answers1

165

Try this

public static bool IsAdministrator()
{
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

This looks functionally the same as your code, but the above is working for me...

doing it functionally, (without unnecessary temp variables) ...

public static bool IsAdministrator()
{
   return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
             .IsInRole(WindowsBuiltInRole.Administrator);
}  

or, using expression-bodied property:

public static bool IsAdministrator =>
   new WindowsPrincipal(WindowsIdentity.GetCurrent())
       .IsInRole(WindowsBuiltInRole.Administrator);
infografnet
  • 3,749
  • 1
  • 35
  • 35
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
  • 21
    Make sure to include "using System.Security.Principal;" – LightLabyrinth Jan 22 '13 at 16:02
  • 2
    Worked for me on Windows 10. – Alexander Sep 16 '17 at 08:42
  • 4
    You need to wrap it in a using statement: "using (var identity = WindowsIdentity.GetCurrent())" – zezba9000 Jan 01 '18 at 22:59
  • 13
    This is always true if the user is an Administrator. It does not distinguish elevated (run as Administrator, so poorly/confusingly worded by Microsoft). – Bob Denny Sep 11 '18 at 18:15
  • 2
    This is only true if the user is Administrator and running the code elevated. In an Admin Command prompt, it will return true. In a non admin command prompt it will return false. – Xavier John Jul 24 '19 at 20:41
  • In my wpf application this returns true if i right click and 'Run as Admin' and returns false if i run it normally. So this checks both the user and the apps rights i think. – Zaki Choudhury Apr 24 '20 at 06:13
  • Best is the second option! – SWIK May 06 '20 at 17:26
  • Accoding to Microsoft's documentation, IsInRole() method only determines whether the current principal belongs to a specified Windows user group (in this case Administrators), not whether process token is elevated. – Igor Levicki Jul 22 '21 at 10:20