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

3

The following code attempts to be able to open an executable file so that you can pass arguments to it once it has been opened.

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

  

Unhandled exception: Required operation requires elevation

When set to p.StartInfo.UseShellExecute = true , the error returned is:

  

Unhandled Exception: The Process object must have the   UseShellExecute property set to false to be able to   redirect I / O streams.

With this in mind, excluding the redirectors and therefore the argument that would be passed to the executable, it is only in this scenario that the executable can be opened. 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();            
} 
    
asked by anonymous 27.09.2018 / 18:59

1 answer

2

Second this answer in 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);
}

But they suggested something seemingly better in other answer .

    
27.09.2018 / 19:04