Reputation: 71
I need to invoke an exe using System.Diagnostics.Process.Start(processInfo)
and want to get some value return back.Based on return value i need to perform further operation. Exe is getting invoked and performing the task accurately, but i am not able to get return value back. Code gets stuck after process.Start()
no exception or warning.
string arguments = arg[0]+ " " + arg[1] + " " + arg[2] + " " + arg[3];
string consoleExePath = @"C:\Test\Console.exe";
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.RedirectStandardOutput = true;
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = Path.GetDirectoryName(consoleExePath);
processInfo.Arguments = string.Format("/c START {0} {1}", Path.GetFileName(consoleExePath), arguments);
System.Diagnostics.Process p = System.Diagnostics.Process.Start(processInfo);
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
int result = p.ExitCode; // always 0
Code inside exe:
static int Main(string[] args)
{
var flag = 0;
flag= objTest.DoSomething(args[0],args[1], args[2], args[3]);
//Console.WriteLine("Process completed!");
//Console.Read();
//return flag;
return 44; // a non zero value.
}
Edit: Due to Console.Read();
, code execution got stuck. thanks to schnaader for catching the silly mistake. But var output = p.StandardOutput.ReadToEnd();
is still empty. tried int result = p.ExitCode;
and result
is always 0
.
Upvotes: 0
Views: 599
Reputation: 49739
Your code works for me. Note that in your .exe code, there is a line:
Console.Read();
So the program will wait for the user to enter a line, and only exit after that. If you don't do this, the other code will wait for the application to terminate like you described.
So you should remove that line and try again.
Another possibility that Christian.K noted in the comments is to redirect standard input using processInfo.RedirectStandardInput = true
. This way, you won't have to modify the .exe code. After that, you can redirect things to the standard input of your .exe, see MSDN for a full example.
Upvotes: 2