How to determine whether application has administrator rights in C#
By FoxLearn 7/3/2024 8:05:47 AM 272
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.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#