C# 以管理员身份运行新进程并读取标准输出
我想允许用户从我的非管理员程序中以管理员身份运行命令行实用程序,并让我的程序获得输出。该实用程序是第三方的,但与我的程序一起分发 我可以,我可以,但我不能同时做这两件事 目前我唯一能做的就是使用cmd.exe将输出重定向到一个文件,例如:C# 以管理员身份运行新进程并读取标准输出,c#,C#,我想允许用户从我的非管理员程序中以管理员身份运行命令行实用程序,并让我的程序获得输出。该实用程序是第三方的,但与我的程序一起分发 我可以,我可以,但我不能同时做这两件事 目前我唯一能做的就是使用cmd.exe将输出重定向到一个文件,例如: using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Reflection; string appDirectory = Path.GetDir
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。肯定有更好的方法可以做到这一点?不要通过新的
cmd
执行,而是尝试直接执行该实用程序。而不是重定向到文件,而是重定向标准输出以从程序中读取它。
为了以管理员身份运行,您需要使用管理员用户名和密码(取自)。您需要将您的方法设置为不安全
:
unsafe public static void Main(string[] args){
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// set admin user and password
p.StartInfo.UserName = "adminusername";
char[] chArray = "adminpassword".ToCharArray();
System.Security.SecureString str;
fixed (char* chRef = chArray) {
str = new System.Security.SecureString(chRef, chArray.Length);
}
p.StartInfo.Password = str;
// run and redirect as usual
p.StartInfo.FileName = utilityPath;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
}
虽然我还没有测试过,但它确实很神奇
它是用C++编写的,但是可以很容易地用C语言编写一个包装器API,用<代码> dLimPult > .< /P>如果你感兴趣的是如何捕获另一个进程的输出,那么这是一个重复的问题;我想我没有弄清楚的是特权的区别。我的应用程序以标准用户身份运行,实用程序以管理员身份运行。据我所知,重定向输出的常规方法在这种情况下不起作用。您应该使用
using(Process p=new Process())
或在p.WaitForExit()
之后调用p.Dispose()
。我收到错误“Process对象必须将UseShellExecute属性设置为false才能重定向IO流”。所以我添加了“p.StartInfo.UseShellExecute=false;”,但这会停止它作为管理员运行:“请求的操作需要提升”。所以我必须向用户询问管理员用户名和密码,而不是使用UAC?他们必须激活管理员帐户并设置密码?如果有更好的方法,恐怕我不知道,我已经接受了这个答案,因为它确实回答了这个问题,但总的来说,我想我会坚持我原来的想法。要求一个管理员帐户是不实际的。