Reading/Writing to a command line program in c#

后端 未结 3 773
夕颜
夕颜 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条回答
  •  Happy的楠姐
    2021-01-16 00:23

    What you're trying to do is to "redirect" the standard input and output channels for the process that you're launching. This will allow you to read from and write to the child process via C# streams.

    To do so, you first need to set the RedirectStandardInput and RedirectStandardOutput fields in the ProcessStartInfo class you use to start the child process:

    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "otherprogram.exe";
    p.Start();
    

    Once that's done, p.StandardInput and p.StandardOutput will be StreamReaders that are attached to the input and output of the child process. Depending on the exact input and output of the child process, you may need to be careful to avoid deadlocking (where your program is waiting for output while the other program is waiting for input, as an example). To avoid that, you can use the BeginOutputReadLine method to receive output asynchronously, if needed.

提交回复
热议问题