Redirect standard output and prompt for UAC with ProcessStartInfo

后端 未结 2 557
清酒与你
清酒与你 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()
    
    0 讨论(0)
  • 2020-12-06 16:14

    UseShellExecute must be set to false to redirect IO, and to true to use the Verb property. So you can't.

    But this article seems do the magic, although I haven't tested it.

    It's written in C++, but a wrapper API can easily be created to be called from C# by using DllImport.


    Note: If you want to pass data between the two programs and have access to the target program's source code, you can easily re-design you application to use Named Pipes instead of redirecting standard I/O.

    0 讨论(0)
提交回复
热议问题