2015-01-04 37 views
1

我正在写一个应该运行一个进程并将输出结果输出到控制台或文件的c#程序。 但我想运行的exe必须以admin身份运行。
我看到要运行一个EXE作为管理员我需要将useShellExecute设置为true。但为了启用输出重定向,我需要将其设置为false。获取输出的elevaed exe

我该怎么做才能实现两者? 谢谢!

在这段代码中,我得到了打印到控制台的错误(因为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);   
       } 
+0

这可能是相关的:http://stackoverflow.com/questions/18660014/redirect-standard-output-and-prompt-for-uac -with-processstartinfo/19381478#19381478 – supertopi 2015-01-04 13:23:30

+0

我不太了解它。它非常长,并在C++中。我不想让这个问题变得更复杂。 – 2015-01-04 13:36:15

+0

这是不可能的。调用Process.Start()的进程必须自行提升。既然你的确不是,你必须写一个帮助程序,要求在其清单中提升。你可以毫无问题地开始一个。然后它可以进行重定向。 – 2015-01-04 13:48:21

回答

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