926
votes

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

13
Besides what Binary Worrier wrote, you might want to write some code to test if you have admin privileges .. (is that what you are asking for?)lexu
I would not take this task lightly though, you should verfiy what it actually needs admin for and see if you can work around it. No customer is going to be happy running an app in admin mode all the time. Alot of bigger customers won't even consider an app like that, and if logo testing matters to you it will not pass like that.Alex
Alex is very much on point. If possible, only elevate when necessary, otherwise, Group Policy, UAC and a number of other variables come into play. At the very least, with UAC, the user would have to authorize on every run as opposed to only when a specific user action is performed.Anthony Mason
The correct way is to embedd a manifest file into your application.Elmue

13 Answers

1200
votes

You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:

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

The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.

157
votes

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).

109
votes

The detailed steps are as follow.

  1. Add application manifest file to project
  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

64
votes

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;
}
43
votes

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).

20
votes

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.

14
votes

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);
}
13
votes

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
12
votes

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.

11
votes

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.

8
votes

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;
    }
}
0
votes

In case you want a code-only solution for some reason, just call "AdminRelauncher.RelaunchIfNotAdmin()" at startup:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;

public static class AdminRelauncher
{
    public static void RelaunchIfNotAdmin()
    {
        if (!RunningAsAdmin())
        {
            Console.WriteLine("Running as admin required!");
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Assembly.GetEntryAssembly().CodeBase;
            proc.Verb = "runas";
            try
            {
                Process.Start(proc);
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
                Environment.Exit(0);
            }
        }
    }

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

        return principal.IsInRole(WindowsBuiltInRole.Administrator);              }
    }
-5
votes

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'.