-1

Hi I am trying to write a C# program such that the CMD opens as administrator then an executable is ran with parameters. The code below works so far as to open CMD (in admin mode), but cPath is my path to the executable. The problem is I cannot pass arguments to the executable. Is there special syntax?

             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();
Eye Van
  • 11
  • 2

2 Answers2

2

In case of cmd.exe, you need to pass it via /c parameter. So in your case it would be:

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();
EylM
  • 5,967
  • 2
  • 16
  • 28
0

You could do something like this that launches the command line without a window and captures the text output.

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";
}
Paul Baxter
  • 1,054
  • 12
  • 22