How to open an executable that requires elevation via C#?

Asked

Viewed 326 times

3

The code provided below seeks to be able to open an executable file so that it is possible to pass arguments to it once it has been opened.

For the code as it is displayed, error returned is:

Untreated exception: Requested operation requires upgrade

Already when configured p.StartInfo.UseShellExecute = true, the error returned is:

Untreated Exception: The Process object must have the Useshellexecute property set to false for power redirect I/O flows.

Having this in view, excluding the redirectors and consequently, the argument that would be passed to the executable, only in this scenario it is possible to open the executable. A first positive but not yet satisfactory result.

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 answer

2


Second that response in the OS:

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 in the Github for future reference.

But they suggested something apparently better in another answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.