Reading/Writing to a command line program in c#

后端 未结 3 769
夕颜
夕颜 2021-01-16 00:09

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

>

3条回答
  •  既然无缘
    2021-01-16 00:29

    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).

提交回复
热议问题