This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 1.1

Check if a Program is Running as an Administrator

User Account Control (UAC) protects Vista by preventing programs from performing administrative or system functions without prior permission. Before attempting such a function, you should check whether your software is running with elevated privileges.

User Account Control

Microsoft Vista introduced User Account Control (UAC). This system limits software by providing only standard privileges, even if the user is logged into the operating system as an administrator. If a program attempts to perform a restricted action, the process is blocked until manually authorised by the user. This helps to prevent attacks from viruses and other malware.

When a program is running as an administrator, either because it was started in that fashion or because it has already requested and received elevated privileges, it may behave differently. For example, Vista dialog boxes with buttons that perform administrative functions show a shield icon alongside the button text. When running as an administrator, the icon is not displayed.

In this article, we will demonstrate how to check if the current program is running with administrative privileges. The example code uses classes from the System.Security.Principal namespace. To simplify the code, it is assumed that you have included the following using directive in the code:

using System.Security.Principal;

WindowsPrincipal Class

The WindowsPrincipal class provides methods that permit you to check whether a user exists within Windows user groups, including checking for built-in roles, such as the administrator role. We will use the IsInRole method, which returns a Boolean value, to check whether the current user is running with administrative privileges.

To create a WindowsPrincipal object for the current user, we will obtain the current user as a WindowsIdentity object. This object can then be passed to a parameter of a WindowsPrincipal constructor before executing the method and holding the result in a Boolean variable for later use. If the Boolean variable has a value of true then the program is running as an administrator. If false, some Windows functions will be unavailable.

The final code for the test is as follows. NB: To test the code, add a means to output the Boolean variable then compile the program in Release mode. You can then run the executable file normally or as an administrator to see the test working.

bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
28 March 2009