![](/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.