Write a C # program to run with administrator rights under Win7

Source: Internet
Author: User

Vista and Windows 7 operating systems to enhance security, the UAC (user Account Control) mechanism is added, and if UAC is turned on and the user is logged on with administrator privileges, the application by default cannot write to the system directory, system registry, and other settings that may affect the system's operation. This mechanism greatly enhances the security of the system, but for application developers, we cannot force users to turn off UAC, but sometimes the applications we develop need to be run by the administrator, that is, running as administrator in Win7, So how do we achieve this function?

When we run some setup programs under Win7, we find that we first pop up a dialog box to let the user confirm whether they agree to allow this program to change your computer configuration, but the application we write by default will not eject this prompt or run with administrator privileges. This article describes how the C # program is set up to prompt the user to run with administrator privileges.

First, add a application Manifest File to the project

The default configuration is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" > <assemblyidentity version= "1.0.0.0" Myapplication.app "/> <trustinfo xmlns=" Urn:schemas-microsoft-com:asm.v2 "> <security> <reques  Tedprivileges xmlns= "Urn:schemas-microsoft-com:asm.v3" > <!--UAC Manifest Options If you are want to Change the Windows User Account Control level, replace the requestedExecutionLevel node with one of the follow
        Ing. <requestedexecutionlevel level= "Asinvoker" uiaccess= "false"/> <requestedexecutionlevel "level="
            Dministrator "uiaccess=" false "/> <requestedexecutionlevel level=" highestavailable "uiAccess=" false "/>  If you are want to utilize File and Registry virtualization for backward compatibility then delete the
        requestedExecutionLevel node. --> <requestedexecutionlevel level= "Asinvoker" uiaccess= "false"/>ges> </security> </trustInfo> </asmv1:assembly>
 

We can see that there is a requestedExecutionLevel entry in this configuration that configures the execution permission level for the current application request. This item has 3 values to choose from, as shown in the following table:

The
Value Description Comment
asinvoker Th E application runs with the same access token as the parent process.  recommended for standard user appli Cations. Do refractoring with internal elevation points, as per the guidance provided, earlier in this document.
highestavailable The application runs with the highest privileges the current user can OBT Ain. recommended for Mixed-mode applications. Refractor the application in a future release.
requireadministrator The application runs only for administrators and requires this AP Plication be launched with the full access token of an administrator. recommended for administrator is only applications. Internal elevation points are not needed. The application is already running elevated.

Asinvoker: If you choose this, the application is running with the current permissions.

Highestavailable: This is run with the highest privileges available to the current user.

Requireadministrator: This is run only with system administrator privileges.

By default, it is asinvoker.

Both the highestavailable and Requireadministrator options can prompt the user for system administrator privileges. So what's the difference between the two options?

The difference is that if we are not logged on as an admin account, then if the application is set to Requireadministrator, then the application runs directly and fails to start. If set to Highestavailable, the application can run successfully, but run with the privileges of the current account rather than system administrator privileges. If we want the program to run when the Non-administrator is logged in (in this case some of the features should be limited), then it is recommended to use highestavailable to configure it.

For authoritative documentation on requestedExecutionLevel settings, refer to the link below:

Create and Embed an application Manifest (UAC)

The following are the modified configuration files:

<?xml version= "1.0" encoding= "Utf-8"?>
xmlns:asmv1= "Urn:schemas-microsoft-com:asm.v1" xmlns:asmv2= "Urn:schemas-microsoft-com:asm.v2"
 xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" > <assemblyidentity version= "1.0.0.0" Myapplication.app "/> <trustinfo xmlns=" Urn:schemas-microsoft-com:asm.v2 "> <security> <reques  Tedprivileges xmlns= "Urn:schemas-microsoft-com:asm.v3" > <!--UAC Manifest Options If you are want to Change the Windows User Account Control level, replace the requestedExecutionLevel node with one of the Follo
        Wing. <requestedexecutionlevel level= "Asinvoker" uiaccess= "false"/> <requestedexecutionlevel "level="
            Dministrator "uiaccess=" false "/> <requestedexecutionlevel level=" highestavailable "uiAccess=" false "/> If you want to utilize File and Registry virtualization for backward compatibility then delete th
        e requestedexecutionlevel node. --> <requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/>questedprivileges> </security> </trustInfo> </asmv1:assembly>
 
After the configuration file is modified, we run the application and the Prompt box pops up first, and then the program can continue to run and gain the privileges of the system administrator.
. Csharpcode,. csharpcode Pre {font-size:small; color:black; Font-family:consolas, "Courier New", Courier, monospace; b Ackground-color: #ffffff; /*white-space:pre;*/} csharpcode pre {margin:0em}. csharpcode. rem {color: #008000;} csharpcode. kwrd {color: # 0000FF; }. csharpcode. str {color: #006080; csharpcode. op {color: #0000c0;} csharpcode. preproc {color: #cc6633; cshar Pcode. asp {background-color: #ffff00;}. csharpcode. html {color: #800000; csharpcode. attr {color: #ff0000; csh Arpcode. alt {background-color: #f4f4f4; width:100%; margin:0em; csharpcode. lnum {color: #606060;}

Let's take a look at how the program knows whether it is currently running under system administrator or non-system administrator rights:

        public static bool Isadministrator ()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent ();
            WindowsPrincipal principal = new WindowsPrincipal (identity);
            return principal. IsInRole (Windowsbuiltinrole.administrator);
        }
. Csharpcode,. csharpcode Pre {font-size:small; color:black; Font-family:consolas, "Courier New", Courier, monospace; b Ackground-color: #ffffff; /*white-space:pre;*/} csharpcode pre {margin:0em}. csharpcode. rem {color: #008000;} csharpcode. kwrd {color: # 0000FF; }. csharpcode. str {color: #006080; csharpcode. op {color: #0000c0;} csharpcode. preproc {color: #cc6633; cshar Pcode. asp {background-color: #ffff00;}. csharpcode. html {color: #800000; csharpcode. attr {color: #ff0000; csh Arpcode. alt {background-color: #f4f4f4; width:100%; margin:0em; csharpcode. lnum {color: #606060;}

This code can be used to determine whether the current program is running under System administrator privileges. If configured as Asinvoker, this function returns false under Win7, and returns True if it is requireadministrator .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.