![](/img/trans.png)
[英]Redirect output using Process in c# with > in ProcessStartInfo.Arguments
[英]Redirect standard output and prompt for UAC with ProcessStartInfo
我正在開發針對.NET 3.0的WPF應用程序。 我需要調用一個需要管理特權的exe。 我可以使用以下方法讓UAC提示許可:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.UseShellExecute = true;
startInfo.FileName = "target.exe";
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
我的問題是我需要重定向標准輸出,並且使用UseShellExecute = true
這樣做會導致異常,說明:
Process對象必須將UseShellExecute屬性設置為false才能重定向IO流
但是,將其設置為false會導致UAC不提示許可,並且出現異常,說明:
請求的操作需要提升
如何重定向標准輸出並提示輸入UAC?
我已經看到了類似的問題 ,但是解決方案是使用app.manifest賦予我的應用程序管理權限。 由於要求,這是我無法做到的。
UseShellExecute
必須設置為false
才能重定向IO,設置為true
才能使用Verb
屬性。 所以你不能。
但是,盡管我尚未對其進行測試,但本文似乎具有魔力。
它是用C ++編寫的,但是可以使用DllImport
輕松創建包裝API以便從C#調用。
注意:如果要在兩個程序之間傳遞數據並有權訪問目標程序的源代碼,則可以輕松地重新設計應用程序以使用Named Pipes
而不用重定向標准I / O。
還有另一個非常簡單的解決方案:
如果要運行子級可執行的提升權限並重定向輸出(可選地包括窗口隱藏),那么您的主代碼也必須運行提升權限。 這是安全要求 。
要做到這一點:
現在,您的代碼將提升運行,其啟動的所有內容也將提升,您還可以捕獲輸出流。 這是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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.