Redirect standard output and prompt for UAC with ProcessStartInfo

后端 未结 2 566
清酒与你
清酒与你 2020-12-06 15:26

I\'m working on a WPF application targeting .NET 3.0. I need to call an exe which requires administrative privileges. I can get the UAC to prompt for permission by using som

2条回答
  •  执笔经年
    2020-12-06 15:52

    There is another pretty simple solution:

    If you want to run a child-executable elevated AND redirect the output (optionally including window hiding), then your main code must be running elevated too. This is a security requirement.

    To accomplish this:

    1. Manually edit your ´app.manifest´ in your project folder.
    2. Find the comment regarding UAC Manifest Options, you will see the 3 examples of ´requestedExecutionLevel´.
    3. Under the comment, locate the tricky ´asInvoker´ which is currently enabled, and replace it with ´requireAdministrator´.
    4. Restart Visual Studio in order to take into effect, and after re-building your app it should have the typical UAC shield icon.

    Now your code will run elevated, everything that it launches will be elevated too, and you can also capture output streams. Here is an example in VB.NET:

    Dim startInfo As New ProcessStartInfo
    startInfo.Verb = "runas"
    startInfo.FileName = "subprocess-elevated.exe"
    startInfo.Arguments = "arg1 arg2 arg3"
    startInfo.WorkingDirectory = Environment.CurrentDirectory
    startInfo.WindowStyle = ProcessWindowStyle.Hidden
    startInfo.CreateNoWindow = True
    Dim p As Process = New Process()
    p.StartInfo = startInfo
    p.StartInfo.UseShellExecute = False
    p.StartInfo.RedirectStandardOutput = True
    p.StartInfo.RedirectStandardError = True
    p.Start()
    Console.WriteLine(p.StandardOutput.ReadToEnd)
    Console.WriteLine(p.StandardError.ReadToEnd)
    p.WaitForExit()
    

提交回复
热议问题