How to determine whether application has administrator rights in C#
By FoxLearn 7/3/2024 8:05:47 AM 411
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#