Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a Process as administrator mode in C# [duplicate]

Tags:

c#

.net

I have a Visual Studio Windows app project. I've added code to download an installer update file. The installer after it has finished downloading would need administrator privileges to run. I have added a manifest file.

When user clicks on the DownloadUpdate.exe, UAC prompts the user for Admin permissions. So I assumed that all processes created and called within DownloadUpdate.exe will run in admin capacity. So I made the setup call my downloaded file with the following code:

Process p = new Process(); p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.FileName = strFile; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; 
like image 570
RPS Avatar asked Mar 28 '10 11:03

RPS


People also ask

How do I set vs Run as administrator?

Run Visual Studio as an administratorOpen the Start menu, and scroll to Visual Studio. From the right-click or context menu of Visual Studio 2019 or Visual Studio 2022, select More > Run as administrator.

How do I force my .NET application to run as administrator?

Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.


2 Answers

Try this:

//Vista or higher check if (System.Environment.OSVersion.Version.Major >= 6) {    p.StartInfo.Verb = "runas"; } 

Alternatively, go the manifest route for your application.

like image 125
Nick Craver Avatar answered Sep 29 '22 00:09

Nick Craver


First of all you need to include in your project

using System.Diagnostics; 

After that you could write a general method that you could use for different .exe files that you want to use. It would be like below:

public void ExecuteAsAdmin(string fileName) {     Process proc = new Process();     proc.StartInfo.FileName = fileName;     proc.StartInfo.UseShellExecute = true;     proc.StartInfo.Verb = "runas";     proc.Start(); } 

If you want to for example execute notepad.exe then all you do is you call this method:

ExecuteAsAdmin("notepad.exe"); 
like image 38
drgmak Avatar answered Sep 28 '22 23:09

drgmak