Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture response returned by EXE file C#

Tags:

c#

i want to pass param to another exe file which is also developed by c#. i know how to pass parameter to exe file from my application. this way i can pass param to exe file

Process p= new Process();
p.StartInfo.FileName = "demo.exe";
p.StartInfo.Arguments = "param1 param2";
p.Start();
p.WaitForExit();

now demo.exe file will do some job and will return some data. i want to capture that data at my end. so guide what i alter in my code to capture response return by demo.exe file. help me with altered code. thanks

probably below solution may solve my issue. i will test it. When you create your Process object set StartInfo appropriately:

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}
like image 816
Mou Avatar asked Dec 20 '25 23:12

Mou


2 Answers

One possible solution is to use RedirectStandardOutput and store your result in a file:

using(Process proc = new Process())
{
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.FileName = <your exe>;
    proc.StartInfo.Arguments = <your parameters>;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.OutputDataReceived += LogOutputHandler;
    proc.Start();
    proc.BeginOutputReadLine();
    proc.WaitForExit();
}

private static void LogOutputHandler(object proc, DataReceivedEventArgs outLine)
{
    <write your result to a file here>
}
like image 154
David Brabant Avatar answered Dec 23 '25 11:12

David Brabant


The easy solution is the old-fashioned process exit code.

You can use p.ExitCode to capture the result in your code once the process has terminated.

Also, demo.exe needs to set Environment.ExitCode before exiting.

Typically, 0 is used to report success.

like image 42
Pascal Avatar answered Dec 23 '25 11:12

Pascal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!