【问题标题】:Run new process as admin and read standard output以管理员身份运行新进程并读取标准输出
【发布时间】:2013-04-01 15:51:27
【问题描述】:

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

我可以redirect the output of a programrun 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#


【解决方案1】:

不要通过新的cmd 执行,而是尝试直接执行该实用程序。而不是重定向到文件,而是重定向标准输出以从您的程序中读取它。 为了以管理员身份运行,您需要使用管理员用户名和密码(取自 here)。您需要将方法设置为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();
}

【讨论】:

  • 您应该使用using(Process p = new Process()) 或在p.WaitForExit() 之后调用p.Dispose()
  • 我收到错误消息“进程对象必须将 UseShellExecute 属性设置为 false 才能重定向 IO 流”。所以我添加“p.StartInfo.UseShellExecute = false;”但这会阻止它以管理员身份运行:“请求的操作需要提升”。
  • 所以我必须向用户询问管理员用户名和密码,而不是使用 UAC?他们必须激活管理员帐户并设置密码?
  • 如果有更好的方法恐怕我不知道
  • 我接受了这个答案,因为它确实回答了这个问题,但总的来说,我认为我会坚持我最初的想法。要求一个管理员帐户实际上并不实际。
【解决方案2】:

This 有魔力,虽然我还没有测试过。

它是用 C++ 编写的,但可以通过使用 DllImport 轻松创建包装 API 以从 C# 中调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 2014-04-26
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多