Programmatically Elevating Process Privileges in C#
Many applications require elevated privileges to perform certain tasks, such as installing services using InstallUtil.exe
. The standard Process.Start
method, however, runs with the application's default permissions. This article demonstrates how to execute processes with elevated privileges in C#.
Consider the following code snippet:
<code class="language-csharp">ProcessStartInfo startInfo = new ProcessStartInfo(m_strInstallUtil, strExePath); System.Diagnostics.Process.Start(startInfo);</code>
This code launches a process with standard user permissions. To elevate privileges, modify startInfo
:
<code class="language-csharp">startInfo.UseShellExecute = true; startInfo.Verb = "runas";</code>
Setting UseShellExecute
to true
and Verb
to "runas"
instructs the system to launch the process with elevated permissions, similar to right-clicking and selecting "Run as administrator." This method triggers the User Account Control (UAC) prompt, requiring user confirmation.
For scenarios where UAC prompts are undesirable, embedding an application manifest is recommended. Requesting the "highestAvailable" execution level in the manifest will prompt UAC upon application launch, granting elevated privileges to all subsequent child processes without further interruptions. This provides a more seamless user experience.
The above is the detailed content of How Can I Programmatically Run Processes with Elevated Privileges in C#?. For more information, please follow other related articles on the PHP Chinese website!