How to determine whether application has administrator rights in C#
By FoxLearn 7/3/2024 8:05:47 AM 201
The System.Security.Principal
namespace in C# provides essential classes for managing and accessing security-related information about the current user's context in a Windows environment.
You can easily create a method to check if the current user belongs to the Administrator role.
public static bool IsAdministrator() { using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } }
You can use it as follows.
bool isAdmin = IsAdministrator(); if (isAdmin) { Console.WriteLine("The application is running with administrator rights."); } else { Console.WriteLine("The application is NOT running with administrator rights."); }
Use the WindowsIdentity.GetCurrent() method to retrieve the identity of the current Windows user, then creates a WindowsPrincipal
object using the current user's identity.
Use principal.IsInRole(WindowsBuiltInRole.Administrator) to help you check whether the current user belongs to the Administrator role.
The IsAdministrator()
method returns true
if the application is running with administrator rights, and false
otherwise.