2015-01-04 38 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 
     } 
    } 
}