C# Check if run as administrator

C#Windows

C# Problem Overview


> 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))
{
    ...
}

C# Solutions


Solution 1 - C#

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEClaessonView Question on Stackoverflow
Solution 1 - C#Charles BretanaView Answer on Stackoverflow