获得elevaed exe的输出

时间:2015-01-04 12:50:04

标签: c# process

我正在编写一个应该运行proccess并将输出打印到控制台或文件的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);        
                }

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

#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
        }
    }
}