【发布时间】:2013-04-01 15:51:27
【问题描述】:
我想允许用户在我的非管理员程序中以管理员身份运行命令行实用程序,并让我的程序获取输出。该实用程序是第三方的,但与我的程序一起分发。
我可以redirect the output of a program 和run a program as administrator,但我不能同时做这两件事。
目前我唯一能做的就是使用 cmd.exe 将输出重定向到文件,例如:
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Reflection;
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string utilityPath = Path.Combine(appDirectory, "tools", "utility.exe");
string tempFile = Path.GetTempFileName();
Process p = new Process();
// hide the command window
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = "cmd.exe";
// run the tool, redirect the output to the temp file and then close.
p.StartInfo.Arguments = " /C \"\"" + utilityPath + "\" > \"" + tempFile + "\"\"";
p.StartInfo.Verb = "runas"; // run as administrator
p.Start();
p.WaitForExit();
// get the output, delete the file and show the output to the user
string output = File.ReadAllText(tempFile);
File.Delete(tempFile);
MessageBox.Show(output);
这有两个问题:1) 它使用临时文件,2) UAC 用于 cmd.exe 而不是 utility.exe。肯定有更好的方法来做到这一点?
【问题讨论】:
-
如果你感兴趣的只是如何捕捉另一个进程的输出,那么这是一个重复的问题;参见例如How to capture the standard output/error of a Process.Start()?.
-
我认为我没有说清楚的是特权差异。我的应用程序以标准用户身份运行,实用程序以管理员身份运行。据我所知,在这种情况下重定向输出的正常方法不起作用。
标签: c#