How to determine whether application has administrator rights in C#
By FoxLearn 7/3/2024 8:05:47 AM 101
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 set DataSource for RDLC Report using Report Viewer in C#
- How to Change report in ReportViewer at runtime in C#
- C# Tutorial
- How to Create overlay modal popup in C#
- How to check if file exists on Server in C#
- How to encrypt a password in C#
- How to read excel file in C#
- How to Create a backup SQL Server in C#