如何以admin身份运行CMD,然后在C#中使用参数运行exe

时间:2019-07-30 17:50:38

标签: c# cmd exe

嗨,我正在尝试编写C#程序,以便以管理员身份打开CMD,然后运行带有参数的可执行文件。下面的代码可以打开CMD(在管理员模式下),但cPath是我指向可执行文件的路径。问题是我无法将参数传递给可执行文件。有特殊语法吗?

             Process cmd = new Process();
             ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "c/c " + cPath with argument);
             startInfo.Verb = "runas";
             cmd.StartInfo.UseShellExecute = false;
             cmd.StartInfo = startInfo;
             cmd.Start();

2 个答案:

答案 0 :(得分:1)

对于cmd.exe,您需要通过/c参数传递。 因此,在您的情况下,它将是:

var args = "some_args_to_exe";
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", $"/c \"{cPath}\" \"{args}\"");
startInfo.Verb = "runas";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo = startInfo;
cmd.Start();

答案 1 :(得分:0)

您可以执行以下操作,在没有窗口的情况下启动命令行并捕获文本输出。

static object ResultLock = new object();

/// <summary>
/// 
/// </summary>
/// <param name="executable"></param>
/// <param name="args"></param>
/// <param name="exitCode"></param>
/// <returns></returns>
private static string ExecuteCommand(string executable, string args, out int exitCode)
{
    exitCode = -1;

    // create the process
    var proc = new Process
    {

        EnableRaisingEvents = true,
        StartInfo =
        {
            FileName = executable,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            Arguments = args,
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            Verb = "runas"
        }
    };

    // try to start the process
    try
    {
        proc.Start();
    }
    catch (Exception ex)
    {
        return
            $"Error launching command line {executable}\n\n{ex.Message}";
    }

    var result = false;
    var messageString = new StringBuilder();
    var timeBefore = DateTime.Now;

    // Wait for process
    while (false == result && (DateTime.Now - timeBefore < new TimeSpan(0, 0, 60)))
    {
        result = proc.WaitForExit(100);
        messageString.Append(proc.StandardOutput.ReadToEnd());
    }

    if (result)
    {

        var message = messageString.ToString();

        lock (ResultLock)
        {
            // save the exitcode
            exitCode = proc.ExitCode;
        }

        return message;
    }
    try
    {
        proc.Close();
    }
    catch
    {
        // ignored
    }
    return $"Error {executable} timed out";
}