Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if run as administrator [duplicate]

Tags:

c#

windows

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)) {     ... } 
like image 686
EClaesson Avatar asked Jul 25 '12 23:07

EClaesson


1 Answers

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); 
like image 98
Charles Bretana Avatar answered Oct 01 '22 14:10

Charles Bretana