简体   繁体   中英

How to read/write to Process input/output in C#

I have a console app that prompts for various pieces of information that I want to invoke from C# via the System.Diagnostics.Process.Start() method from a Windows Form app but I can't quite get it to work correctly. As a simple example lets say I want to capture FirstName, and LastName via a Windows Form application and then pass each to the console app dynamically like this:

  1. Forms app launches, the user keys in the values for firstname and lastname and clicks a button to submit
  2. it calls Process.Start for the console app
  3. Console app writes out 'Enter your first name"
  4. Forms app reads this prompt, identifies that it needs to respond with the FirstName value it has collected and writes it to the console app's output
  5. Console app accepts the input and responds with the next prompt "Enter your last name"
  6. Forms app reads this prompt, identifies that it needs to respond with the LastName value it has collected and writes it to the console app's output
  7. Console app now has all the information it needs and continues on its merry way

thanks for any insight, this is not an area I have worked with much at all

From the WinForms app, you can read output from the console app with the StreamReader returned by the Process.StandardOutput property, and write input to the console app with the StreamWriter returned by the Process.StandardInput property.

BTW, did you develop the console app yourself (or have the project files)? If so, I'd suggest using a better form of IPC, such as making the console app a DLL intead of an EXE, or using something from WCF or something like that.

Look at Process.StandardOutput and Process.StandardInput and Process.StandardError .

You need to read from Process.StandardOutput . When you read " 'Enter your first name"" then you write the first name to Process.StandardInput and so on.

Note that the child process can write to its StandardError as well and you probably need to read from it in a different thread so that you can read concurrently from both

In Java there is expect4j that makes this easy. I am pretty sure I saw something on .net but but I am not able to find it right now.

EDIT: Creating a Child Process with Redirected Input and Output seems to be a good article on this topic on MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM