More about C # default run Program sample code as Administrator

Source: Internet
Author: User

One, through the configuration file implementation as administrator to run the program

Vista and Windows 7 operating systems in order to enhance security, the mechanism of UAC (user Account Control) is increased, and if UAC is turned on, even if the user is logged on with administrator rights, its application will not be able to write to the system directory, the system registry, and other settings that may affect the system's operation by default. This mechanism greatly enhances the security of the system, but for the application developer, we cannot force the user to turn off UAC, but sometimes the application we develop needs to run in Administrator mode, that is, Win7 as Administrator. So how do we implement such a function?

When we run some installers under Win7, we find that we first pop up a dialog box to let the user know if they agree to allow this program to change your computer configuration, but the application we write does not pop up this prompt or run with administrator privileges. This article describes how C # programs are 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"? ><asmv1:assembly manifestversion= "1.0" xmlns= "urn: Schemas-microsoft-com:asm.v1 "
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" Name= " Myapplication.app "/> <trustinfo xmlns=" Urn:schemas-microsoft-com:asm.v2 "> <security> <requested Privileges xmlns= "Urn:schemas-microsoft-com:asm.v3" > <!--UAC Manifest Options If you want to Chan        GE the Windows User account Control level replaces the requestedExecutionLevel node with one of the following. <requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/> <requestedexecutionlevel level= "re Quireadministrator "uiaccess=" false "/> <requestedexecutionlevel level=" highestavailable "uiAccess=" false "/ > If you want to utilize File and Registry virtualization for backward compatibility then delete        The requestedExecutionLevel node. --<requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/> </requestedPrivileges> &L T/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 entry has 3 values to choose from, as shown in the following table:

Value Description Comment
AsInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. 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 obtain. Recommended for Mixed-mode applications. Plan to refractor the application in a future release.
Requireadministrator The application runs only for administrators and requires the application is launched with the full access token of a N Administrator. Recommended for administrator only applications. Internal elevation points is 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 only run 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 these two options?

The difference is that if we are not logged in as an administrator account, then if the application is set to Requireadministrator, then the application will fail to run directly and cannot start. If set to Highestavailable, the application can run successfully, but runs with the permissions of the current account instead of system administrator privileges. If we want the program to run when a non-admin account is logged in (in which case some functionality should be limited), we recommend that you configure it with highestavailable.

Please refer to the following links for authoritative documentation on requestedExecutionLevel settings:

Create and Embed an application Manifest (UAC)

The following is the modified configuration file:

<?xml version= "1.0" encoding= "Utf-8"? ><asmv1:assembly manifestversion= "1.0" xmlns= "urn: Schemas-microsoft-com:asm.v1 "
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" Name= " Myapplication.app "/> <trustinfo xmlns=" Urn:schemas-microsoft-com:asm.v2 "> <security> <requested Privileges xmlns= "Urn:schemas-microsoft-com:asm.v3" > <!--UAC Manifest Options If you want to Chan        GE the Windows User account Control level replaces the requestedExecutionLevel node with one of the following. <requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/> <requestedexecutionlevel level= "re Quireadministrator "uiaccess=" false "/> <requestedexecutionlevel level=" highestavailable "uiAccess=" false "/  > If you want to utilize File and Registry virtualization for backward compatibility then delete        The requestedExecutionLevel node. --<requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/> </requestedprivilegEs> </security> </trustInfo></asmv1:assembly> 
After the configuration file changes, we run the application, we will first pop up a prompt box, click Yes, 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;}. Csharpcode. asp {background-color: #ffff00;}  . csharpcode. html {color: #800000;}. Csharpcode. attr {color: #ff0000;}. Csharpcode. alt {background-color: #f4f 4F4; width:100%; Margin:0em; }   . csharpcode. lnum {color: #606060;}


Let's take a look at how the program knows if it is currently running on 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;}. C Sharpcode. asp {background-color: #ffff00;}  . Csharpcode. html {color: #800000;}. Csharpcode. attr {color: #ff0000;}. Csharpcode. alt {background-color: #f4f4f4; w idth: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.

Second, run the program as an administrator by programming

when reading and writing entries under "Hkey_local_machine\software\" in the registry, it is clear that there are in the registry, but the program OpenSubKey always returns NULL, taking into account possible reasons for permissions, so I ran as an administrator once, the results of the test success! Originally really is the problem of permissions, so in the program is added to the default as an administrator to run the code. Let's see how it's going to come true!


Program runs as Administrator by default

static void Main (string[] Args) {/** * When the current user is an administrator, start the application directly * if it is not an administrator, start with the startup object Program to make sure to run as Administrator *//Get the currently logged on Windows user ID System.Security.Principal.WindowsIdentity identi            ty = System.Security.Principal.WindowsIdentity.GetCurrent ();            Create Windows User topic Application.enablevisualstyles ();            System.Security.Principal.WindowsPrincipal Principal = new System.Security.Principal.WindowsPrincipal (identity); Determines whether the currently logged on user is an administrator if (principal.                IsInRole (System.Security.Principal.WindowsBuiltInRole.Administrator)) {//If it is an administrator, run it directly                Application.enablevisualstyles ();            Application.Run (New Form1 ()); } else {//Create startup object System.Diagnostics.ProcessStartInfo StartInfo = new                System.Diagnostics.ProcessStartInfo (); Set the Run file Startinfo.filename = System.Windows.Forms.Application.ExecutablePath;                Set Startup Parameters startinfo.arguments = String.Join ("", Args);                Set the start action to make sure that run as Administrator Startinfo.verb = "runas";                If it is not an administrator, start UAC System.Diagnostics.Process.Start (startinfo);            Exit System.Windows.Forms.Application.Exit (); }        }

Open the Program.cs file in the assembly and replace the code in the main method with the code above to enable the program to run as administrator by default.


Related Article

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.