【发布时间】:2015-01-04 12:50:03
【问题描述】:
我正在编写一个 c# 程序,它应该运行一个进程并将输出打印到控制台或文件。
但是我要运行的exe必须以管理员身份运行。
我看到要以管理员身份运行 exe,我需要将 useShellExecute 设置为 true。但要启用输出重定向,我需要将其设置为 false。
我可以做些什么来实现这两者? 谢谢!
在此代码中,我将错误打印到控制台(因为 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);
}
【问题讨论】:
-
我不是很懂。它很长,而且在 c++ 中。我不想让这个问题变得更复杂。
-
这是不可能的。调用 Process.Start() 的进程必须自行提升。既然你的肯定不是,你必须编写一个小助手程序,在它的清单中请求提升。你可以毫无问题地启动那个。然后它又可以进行重定向。
-
我从未尝试过,但也许您可以调用一个批处理文件,该批处理文件在 DOS 命令中嵌入了输出重定向,例如
runas theAdminID "myCommand.exe > someFile.txt"。然后只需读取文件。 -
感谢您的帮助,但我至少找到了解决方案。我可以以管理员身份运行 vs,或者运行程序 exe。