In this article, we will learn how to force run a .NET application as an Administrator. We will do that by modifying the application manifest file of our application to illustrate the whole process.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Preparation to Run .NET Application as Administrator

To force our application to run as administrator, we need to add and modify an application manifest file. The application manifest is an XML file that provides information about the application to the operating system.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Let’s start by creating a console application AdministratorApp. We can achieve this either using the Console App template in Visual Studio or through the .NET CLI:

dotnet new console -n AdministratorApp --framework net7.0-windows

This article only focuses on applications running on Windows OS, therefore we target the framework net7.0-windows.

Afterward, we need to include an app.manifest file in the project. This file should be located in the root node of the project. In Visual Studio, we accomplish this by right-clicking on our console project, selecting Add and then New Item. Within the Add New Item dialog window that appears, we search for Application Manifest File and add it to our project.

To modify our app.manifest file, we first have to locate the following line:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

Secondly, we update the requestExecutionLevel to:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

The value requireAdministrator is already very descriptive. It tells our application to require administrator privileges.

That’s it. With these changes to our application, we are ready to check if our application runs with administrator privileges.

Checking for Administrator Privileges

Now, let us define an interface that will check whether the current user has administrator privileges:

public interface IAdministratorChecker
{
    bool IsCurrentUserAdmin();
}

The interface IAdministratorChecker has a single-method signature IsCurrentUserAdmin(), which we implement in the AdministratorChecker class:  

public class AdministratorChecker : IAdministratorChecker
{
    public bool IsCurrentUserAdmin()
    {
        var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}

The IsCurrentUserAdmin() method determines whether the current user has administrator privileges or not.

WindowsIdentity is a class in the System.Security.Principal namespace that represents the identity of the Windows user. The WindowsIdentity.GetCurrent() method retrieves the Windows identity of the currently executing process, corresponding to the current user running the application.

A WindowsPrincipal object is then created based on the WindowsIdentityclass, which represents a Windows user’s security context and will allow us to check the roles to which the user belongs. 

The enumeration value WindowsBuiltInRole.Administrator represents the built-in Windows Administrator role. IsCurrentUserAdmin() method consequently returns true if the current user has the WindowsBuiltInRole.Administrator role and false if otherwise.

Printing User Privilege Status to Console

Let’s create a helper class to print our user privilege status:

public static class PrivilegeStatusPrinter
{
    public static void Print(bool isAdmin)
    {
        if (isAdmin)
        {
            Console.WriteLine("The application is running with administrator privileges!");
        }
        else
        {
            Console.WriteLine("The application is not running with administrator privileges.");
        }
    }
}

The PrivilegeStatusPrinter static class contains a PrintPrivilegeStatus() static method that displays to the console whether the application is running with administrator privileges or not.

Now, let’s bring together our AdministratorChecker and PrivilegeStatusPrinter for testing our application:    

var administratorChecker = new AdministratorChecker();
bool isAdmin = administratorChecker.IsCurrentUserAdmin();
PrivilegeStatusPrinter.Print(isAdmin);

In our Program class, we use our previously created AdministratorChecker class to check if our user is an administrator and print the result of it via our created static class, PrivilageStatusPrinter.

Finally, let’s build and run our AdministratorApp using the command line. We will navigate to the directory containing our AdministratorApp project to run the application:

C:\Codes\HowToForceRunDotNetApplicationAsAdministrator\AdministratorApp>dotnet run
Unhandled exception: System.ComponentModel.Win32Exception (740): 
An error occurred trying to start process 
'C:\Codes\HowToForceRunDotNetApplicationAsAdministrator
\AdministratorApp\bin\Debug\net7.0\AdministratorApp.exe' 
with working directory 
'C:\Codes\HowToForceRunDotNetApplicationAsAdministrator\AdministratorApp'. 
The requested operation requires elevation.   
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at Microsoft.DotNet.Cli.Utils.Command.Execute(Action`1 processStarted)
   at Microsoft.DotNet.Tools.Run.RunCommand.Execute()
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass4_0.<<BuildInvocationChain>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.DotNet.Cli.Parser.<>c__DisplayClass17_0.<<UseParseErrorReporting>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.CommandLineBuilderExtensions.<>c__DisplayClass11_0.<<UseHelp>b__0>d.MoveNext()

A System.ComponentModel.Win32Exception exception with the error code 740 occurs. This error code refers to the error The requested operation requires elevation. By implication, we can only run our application using administrator privileges.

To fix this, let’s open the command line with administrator privileges and run our application again:

The application is running with administrator privileges.

Finally, the console output indicates that we have forced our AdministratorApp to run with administrator privileges.

Conclusion

In this article, we have looked at how to force a .NET application to run with administrator privileges by using an app.manifest file. 

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!