I\'m trying to talk to a command-line program from C#. It is a sentiment analyser. It works like this:
CMD> java -jar analyser.jar
>
Here's a little demo showing how to do what you are asking.
This is a toy command line app that just reads from standard input and echos back to standard output:
class Echoer
{
static void Main(string[] args)
{
while (true)
{
var input = Console.ReadLine();
Console.WriteLine("Echoing: " + input);
}
}
}
This is another command line app that runs the above app, passing input to it, and reading its output:
class Program
{
static void Main(string[] args)
{
ProcessStartInfo processStartInfo;
processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
// Redirect IO to allow us to read and write to it.
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.FileName = @"path\to\your\Echoer.exe";
Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
int counter = 0;
while (counter < 10)
{
// Write to the process's standard input.
process.StandardInput.WriteLine(counter.ToString());
// Read from the process's standard output.
var output = process.StandardOutput.ReadLine();
Console.WriteLine("Hosted process said: " + output);
counter++;
}
process.Kill();
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
If the app you are hosting does not simply produce a line of output in response to a line of input, then you can look at capturing output asynchronously using Process.BeginOutputReadLine (there's example code in the linked documentation).