2

I am executing an exe file which contains some c code from my c# winform but I get the complete output of the c code only after the complete execution of exe. I want the exe to relay its output to my winform synchronously (line by line in realtime).

    var proc = new Process
      {
          StartInfo = new ProcessStartInfo
          {
              FileName = "background.exe",
              Arguments = command,
              UseShellExecute = false,
              RedirectStandardOutput = true,
              CreateNoWindow = true
          }
      };


      proc.Start();
      while (!proc.StandardOutput.EndOfStream)
      {
          ConsoleWindow.AppendText(proc.StandardOutput.ReadLine());
          ConsoleWindow.AppendText(Environment.NewLine);

      }
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Dinesh wakti
  • 121
  • 2
  • 8
  • What do you mean `some c code`? No text gets written to output unless the executing *process* put it there. You should check the code of `background.exe`. And make sure that `background.exe` is actually a compiled, binary executable file and not just a C file with a different extension – Panagiotis Kanavos Mar 29 '16 at 11:45
  • Did you checked this [question](http://stackoverflow.com/questions/285760/how-to-spawn-a-process-and-capture-its-stdout-in-net) and this [question](http://stackoverflow.com/questions/18588659/redirect-process-output-c-sharp) ? – Dudi Keleti Mar 29 '16 at 11:51
  • Checked all the code examples and they read the output only after the process is finished. – Dinesh wakti Mar 29 '16 at 12:07

1 Answers1

0

Try this, which is loosely adapted from this example:

    private void button1_Click(object sender, EventArgs e)
    {
        var consoleProcess = new Process
        {
            StartInfo =
            {
                FileName =
                    @"background.exe",
                UseShellExecute = false,
                RedirectStandardOutput = true
            }
        };

        consoleProcess.OutputDataReceived += ConsoleOutputHandler;
        consoleProcess.StartInfo.RedirectStandardInput = true;
        consoleProcess.Start();
        consoleProcess.BeginOutputReadLine();
    }

    private void ConsoleOutputHandler(object sendingProcess,
        DataReceivedEventArgs outLine)
    {
        // This is the method in your form that's 
        // going to display the line of output from the console.
        WriteToOutput(outLine.Data);
    }

Note that the event handler that receives the output from the console is executing on a different thread, so you have to ensure that whatever you use to display the output on your form occurs on the UI thread.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62