获取提升的exe的输出

Getting output of elevaed exe

我正在编写一个 c# 程序,它应该运行一个进程并将输出打印到控制台或文件。 但是我要运行的exe必须以管理员身份运行。
我看到要以管理员身份运行 exe,我需要将 useShellExecute 设置为 true。但要启用输出重定向,我需要将其设置为 false。

我该怎么做才能同时实现这两个目标? 谢谢!

在这段代码中,我将错误打印到控制台(因为 UseShellExecute=false ), 当更改为 true - 程序停止。

                ProcessStartInfo proc = new ProcessStartInfo();
                proc.UseShellExecute = false;
                proc.WorkingDirectory = Environment.CurrentDirectory;
                proc.FileName = "aaa.exe";
                proc.RedirectStandardError = true;
                proc.RedirectStandardOutput = true;        
                proc.Verb = "runas";

                Process p = new Process();
                p.StartInfo = proc;

                p.Start();        

                while (!p.StandardOutput.EndOfStream)
                {
                    string line = p.StandardOutput.ReadLine();
                    Console.WriteLine("*************");
                    Console.WriteLine(line);        
                }

您可以尝试这样的操作:

#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
#endregion


namespace CSUACSelfElevation
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            // Update the Self-elevate button to show a UAC shield icon.
            this.btnElevate.FlatStyle = FlatStyle.System;
            SendMessage(btnElevate.Handle, BCM_SETSHIELD, 0, (IntPtr)1);
        }

        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);

        const UInt32 BCM_SETSHIELD = 0x160C;


        private void btnElevate_Click(object sender, EventArgs e)
        {
            // Launch itself as administrator
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Application.ExecutablePath;
            proc.Verb = "runas";

            try
            {
                Process.Start(proc);
            }
            catch
            {
                // The user refused to allow privileges elevation.
                // Do nothing and return directly ...
                return;
            }

            Application.Exit();  // Quit itself
        }
    }
}