I've seen a ton of articles on Stack Overflow (and the rest of the Internet) for starting a command-line process in the background of a C# application, however all of the examples put a process.WaitForExit()
command at the end.
My issue is that I need to keep the process alive in the background so that my WPF app can communicate with it (client/server style). My code successfully runs the process and my app can communicate with it, but I can't seem to capture any of the output.
Simplified code.
In App.xaml.cs
:
private Process hostApplication;
private FileInfo hostApplicationFilename;
private void Application_Startup(object sender, StartupEventArgs e)
{
// Start the command line process
hostApplication = new Process();
hostApplicationFilename = new FileInfo(@"C:\pretendpath\myEXE.exe");
hostApplication.StartInfo.FileName = hostApplicationFilename.FullName;
hostApplication.StartInfo.WorkingDirectory = hostApplicationFilename.DirectoryName;
hostApplication.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
hostApplication.StartInfo.CreateNoWindow = true;
hostApplication.StartInfo.UseShellExecute = false;
hostApplication.StartInfo.RedirectStandardOutput = true;
hostApplication.StartInfo.RedirectStandardError = true;
hostApplication.StartInfo.RedirectStandardInput = true;
hostApplication.OutputDataReceived += new DataReceivedEventHandler(HostApplicationOutputHandler);
hostApplication.ErrorDataReceived += new DataReceivedEventHandler(HostApplicationOutputHandler);
hostApplication.EnableRaisingEvents = true;
hostApplication.Start();
hostApplication.BeginOutputReadLine();
hostApplication.BeginErrorReadLine();
// Start the WPF's main window
MainWindow view = new MainWindow();
view.Show();
}
private void HostApplicationOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
LocalHostApplicationLog = Environment.NewLine + outLine.Data;
#if (DEBUG)
Console.WriteLine("HOST APPLICATION OUTPUT: " + outLine.Data);
#endif
}
}
If I put a breakpoint inside the DataReceivedEventHandler
, it's never hit.
Any suggestions would be greatly appreciated!