How to open an executable that requires elevation via C#?
The code provided below seeks to be able to open an executable file in such a way that it is possible to pass arguments to it once it has been opened.
For the code as it is presented, Error returned is:
Untreated exception: the requested operation requires elevation
Already when configured p.StartInfo.UseShellExecute = true
, the Error returned is:
Exception without treatment: the process object must have the property Useshellexecute set to false to be able to redirect I/O streams.
With this in mind, excluding redirectors and therefore the argument that would be passed to the executable, only in this scenario is it possible to open the executable. A first positive result, but not yet satisfactory.
private void CreatePorts(object sender, EventArgs e)
{
// Start the child process.
Process p = new Process();
//Set parameters to redirect input/output from the application
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.LoadUserProfile = true;
p.StartInfo.Verb = "runas";
//Hide the application window
//p.StartInfo.CreateNoWindow = true;
//Set the Application Path and Working to directory to the location of setupc.exe
p.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\com0com";
p.StartInfo.FileName = @"setupc.exe";
//Append command and flags and execute the process
p.StartInfo.Arguments = "list";
p.Start();
string output = "";
output += p.StandardOutput.ReadToEnd() + "\r\n";
Console.WriteLine(output);
p.WaitForExit();
}
1 answers
Second this answer in the SO :
if (!IsAdministrator()) {
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator() {
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
I put on GitHub for future reference.
But they suggested something apparently better in another answer.