[c#] How do I force my .NET application to run as administrator?

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?

This question is related to c# .net windows-7 administrator elevated-privileges

The answer is


Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

private static void Main(string[] args)
{
    if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        foreach (string arg in args)
        {
            proc.Arguments += String.Format("\"{0}\" ", arg);
        }

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
        }
        catch
        {
            Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
        }
    }
    else
    {
        //Normal program logic...
    }
}

private static bool IsRunAsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);

    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by @NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}

Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.

If you want to run it as admin for all users, do the same thing in 'change setting for all users'.


While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.

In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:

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

OR

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

OR

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

To set your application to run as administrator, you have to chose the middle one.


I implemented some code to do it manually:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.


Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator
(call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).


You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).


You can create the manifest using ClickOnce Security Settings, and then disable it:

Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings

After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option

Open that file and change this line :

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

to:

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

This will make the program require administrator privileges.


The detailed steps are as follow.

  1. Add application manifest file to solution
  2. Change application setting to "app.manifest"
  3. Update tag of "requestedExecutionLevel" to requireAdministrator.

Adding file in Solution

Select Application Manifest File

Select Manifest option

Update Manifest file

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security


As per

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

you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.

  • Next, right click project
  • Add new Item
  • Last, find and click Application Manifest File

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to windows-7

ng is not recognized as an internal or external command Why am I getting ImportError: No module named pip ' right after installing pip? How to Delete node_modules - Deep Nested Folder in Windows Telnet is not recognized as internal or external command Multiple -and -or in PowerShell Where-Object statement How do I set ANDROID_SDK_HOME environment variable? Run Batch File On Start-up Why isn't .ico file defined when setting window's icon? How to access shared folder without giving username and password Can't start hostednetwork

Examples related to administrator

Google Chrome: This setting is enforced by your administrator How to run vbs as administrator from vbs? Batch Script to Run as Administrator How do I run a program from command prompt as a different user and as an admin What precisely does 'Run as administrator' do? Running a command as Administrator using PowerShell? How do I set a Windows scheduled task to run in the background? Start / Stop a Windows Service from a non-Administrator user account How do I force my .NET application to run as administrator? Psexec "run as (remote) admin"

Examples related to elevated-privileges

How to run python script with elevated privilege on windows How to run vbs as administrator from vbs? How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required? How do I force my .NET application to run as administrator? How to request Administrator access inside a batch file