In one of our previous article, we learned how to force the start of a WinForms C# based application with administrator rights. This is pretty useful when we don't care about the current status of our application when it runs with or without administrator rights. However, when your application needs to run in both conditions, you should check when to run some piece of code according to the condition. This can be easily done through the System.Security.Principal class of Windows.
The System.Security.Principal namespace defines a principal object that represents the security context under which your code is running. When you import this class, you can access the WindowsIdentity class of the namespace. This class represents the current user that runs the application.
With this object, you can check whether the current identity matches the Windows group membership of a Windows user, in this case the Administrator role. Provide as first argument of a new instance of the WindowsPrincipal class. From this object, you can call the IsInRole method to verify if is administrator or not:
using System.Security.Principal;
// Store boolean flag
bool isAdmin;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
// If is administrator, the variable updates from False to True
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// Check with a simple condition whether you are admin or not
if (isAdmin)
{
MessageBox.Show("You have administrator rights !");
}
else
{
MessageBox.Show("You don't have administrator rights :C !");
}
With this simple logic, you can easily check if the current user is administrator or not. Is worth to mention that this works perfectly in Windows and in Mono as well, for Linux environments.
Creating a method
You can easily create a method in your class to verify shortly this logic:
using System.Security.Principal;
/// <summary>
/// Boolean method that verifies if the current user has administrator rights.
/// </summary>
/// <returns></returns>
public bool IsAdministrator()
{
bool isAdmin;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
return isAdmin;
}
You can use it with a conditional:
if (this.IsAdministrator())
{
MessageBox.Show("You have administrator rights !");
}
else
{
MessageBox.Show("You don't have administrator rights :C !");
}
Happy coding !