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

时间:2013-04-01 15:51:27

标签: c#

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

我可以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。肯定有更好的方法吗?

2 个答案:

答案 0 :(得分:3)

尝试直接执行该实用程序,而不是执行新的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();
}

答案 1 :(得分:0)

This虽然没有经过测试,但仍有神奇之处。

它是用C ++编写的,但可以使用DllImport轻松创建一个包装器API,以便从C#调用。