以管理员身份运行新流程并读取标准输出

Chr*_*isD 9 c#

我想允许用户从我的非管理员程序中以管理员身份运行命令行实用程序,并让我的程序获取输出.该实用程序是第三方,但随我的程序一起分发.

我可以重定向程序的输出,我可以作为管理员运行程序,但我不能同时做两个.

我目前唯一可以工作的是使用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);
Run Code Online (Sandbox Code Playgroud)

这有两个问题:1)它使用临时文件和2)UAC用于cmd.exe而不是utility.exe.肯定有更好的方法来做到这一点?

Jul*_*ano 5

cmd尝试直接执行该实用程序,而不是通过new 执行。而不是重定向到文件,而是重定向标准输出以从程序中读取文件。为了以admin身份运行,您需要使用admin用户名和密码(从此处获取)。您需要将方法设置为unsafe

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用using(Process p = new Process())或在p.WaitForExit()之后调用p.Dispose()。 (2认同)
  • 所以我必须向用户询问管理员用户名和密码,而不是使用 UAC?他们必须激活管理员帐户并设置密码? (2认同)