Coder Perfect

What is the best way to make my.NET program run as administrator?


How can I compel my program to run as an administrator on Windows 7 once it has been installed on a client machine?

Asked by Gold

Solution #1

You’ll need to change the manifest file that’s included with the software. This is compatible with Visual Studio 2008 and higher: Project + Add New Item, select “Application Manifest File”. Change the element to:

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

When the user starts the program, the UAC prompt appears. Use caution; their patience can easily wear thin.

Answered by Hans Passant

Solution #2

Including a requestedExecutionLevel element in your manifest is only half the battle; you must also keep in mind that UAC can be disabled. If that’s the case, you’ll have to verify the user for administrator status the old fashioned manner (call IsInRole(WindowsBuiltInRole.Administrator) on your thread’s CurrentPrincipal).

Answered by Anders

Solution #3

The following are the detailed steps.

Note that in order to use this code, you must disable ClickOnce’s security settings. To do so, navigate to Properties -> Security -> ClickOnce Security.

Answered by Hassan Rahman

Solution #4

To accomplish it manually, I wrote some code:

using System.Security.Principal;
public bool IsUserAdministrator()
    bool isAdmin;
        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;

Answered by NG.

Solution #5

You can include a manifest file in the EXE file to make Windows (7 or higher) run the program as an administrator by default.

Step 6: Create and Embed an Application Manifest (UAC) contains more information (MSDN).

Answered by David

Post is based on