TomGeo
TomGeo

Reputation: 1345

How to write a command to cmd.exe when using ProcessStartInfo

I have some script files that would usually be edited and run through a ui, but the offer to run on the command line when using the syntax: program.exe scriptfile.fmw --userparameter "some parameter".

If I simply write

arguments = "program.exe scriptfile.fmw --userparameter \"some parameter\"";
Process process = Process.Start("cmd.exe", $"/K {arguments};
process.WaitForExit();

the commandline starts, calls the correct exe and runs the script.

Now I want to retrieve the response of the script after it ran to catch possible error messages.

As far as I can see this requires to use ProcessStartInfo and that's basically where my problem seems to start.

ProcessStartInfo startInfo = new ProcessStartInfo()
{
    FileName = "cmd.exe",
    Arguments = $"/K {arguments}",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

Process process = Process.Start(startInfo);
process.BeginErrorReadLine();
process.WaitForExit();

The code above opens a commandline window, but never uses the arguments given. It escapes me on how I should hand the argument line over to the cmd.exe - process.

I was playing around with RedirectStandardInput and its StreamWriter, but never managed to get anything written into the cmd-window.

The same goes for the RedirectStandardOutput, where I would like to gather the script response in the cmd-window as a string or string[], to parse for specific exit codes of the script.

Upvotes: 0

Views: 2560

Answers (1)

Rishabh Kumar
Rishabh Kumar

Reputation: 66

I think this is what you want, have a look below :

Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo()
{
    FileName = "program.exe", //You must use your program directly without invoking through cmd.exe
    Arguments = "scriptfile.fmw --userparameter \"some parameter\"", //Add parameters and arguments here needed by your application
    UseShellExecute = false,
    EnableRaisingEvents = true, //You are missing this
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

process.ErrorDataReceived += process_ErrorDataReceived; //You should listen to its output error data by subscribing to this event
process.BeginErrorReadLine();
process.Start(startInfo);
process.WaitForExit(); // You may now avoid this

Then at here do anything with your received error data!

private static void process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
    DoSomething(e.Data); // Handle your error data here
}

EDIT-(1) : Please try this solution and ping me if it works or if you need some extra help. Everyone in comments is suggesting that you must not use cmd.exe to invoke your program as it may causes debugging overhead, performance issue and you might not get error details as well.

Cheers!

Upvotes: 4

Related Questions